必需如果属性不在客户端?

时间:2015-09-17 07:08:46

标签: asp.net-mvc custom-controls

我的问题是它在服务器端是完美的工作,但我希望这个requiredif属性在客户端工作我已经尝试过去2天使用不同的代码但是没有工作。请任何一个帮助找到这个问题的解决方案 我在Validation文件夹中添加了RequierdIf.cs文件,并在模型中使用了这个requiredif属性   这是我的RequierdIF.cs文件

       [AttributeUsage(AttributeTargets.Property)]

            public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
            {
                protected RequiredAttribute _innerAttribute;

                public string DependentProperty { get; set; }
                public object TargetValue { get; set; }

                public bool AllowEmptyStrings
                {
                    get
                    {
                        return _innerAttribute.AllowEmptyStrings;
                    }
                    set
                    {
                        _innerAttribute.AllowEmptyStrings = value;
                    }
                }

                public RequiredIfAttribute(string dependentProperty, object targetValue)
                {
                    _innerAttribute = new RequiredAttribute();
                    DependentProperty = dependentProperty;
                    TargetValue = targetValue;
                }

                protected override ValidationResult IsValid(object value, ValidationContext validationContext)
                {
                    // get a reference to the property this validation depends upon
                    var containerType = validationContext.ObjectInstance.GetType();
                    var field = containerType.GetProperty(DependentProperty);

                    if (field != null)
                    {
                        // get the value of the dependent property
                        var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
                        // trim spaces of dependent value
                        if (dependentValue != null && dependentValue is string)
                        {
                            dependentValue = (dependentValue as string).Trim();

                            if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
                            {
                                dependentValue = null;
                            }
                        }


                        if ((dependentValue == null && TargetValue == null) ||
                            (dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
                        {
                            // match => means we should try validating this field
                            if (!_innerAttribute.IsValid(value))

                                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
                        }
                    }

                    return ValidationResult.Success;
                }

                public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
                {
                    var rule = new ModelClientValidationRule
                    {
                        ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                        ValidationType = "requiredif",

                    };



                    string depProp = BuildDependentPropertyId(metadata, context as ViewContext);


                    string targetValue = (TargetValue ?? "").ToString();
                    if (TargetValue is bool)
                        targetValue = targetValue.ToLower();

                    rule.ValidationParameters.Add("dependentproperty", depProp);
                    rule.ValidationParameters.Add("targetvalue", targetValue);

                    yield return rule;
                }

                private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
                {

                    string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);

                    var thisField = metadata.PropertyName + "_";
                    if (depProp.StartsWith(thisField))

                        depProp = depProp.Substring(thisField.Length);
                    return depProp;
                }


            }

这里是我的jquery文件jquery.validate.requiredif.js:

        (function ($) {

        $.validator.addMethod('requiredif',
            function (value, element, parameters) {
                var id = '#' + parameters['dependentproperty'];


                var targetvalue = parameters['targetvalue'];
                targetvalue = (targetvalue == null ? '' : targetvalue).toString();


                var control = $(id);
                var controltype = control.attr('type');
                var actualvalue =
                    (controltype === 'checkbox' ||  controltype === 'radio')  ?
                    control.attr('checked').toString() :
                    control.val();


                if ($.trim(targetvalue) === $.trim(actualvalue) || ($.trim(targetvalue) === '*' && $.trim(actualvalue) !== ''))
                    return $.validator.methods.required.call(
                      this, value, element, parameters);

                return true;
            });

        $.validator.unobtrusive.adapters.add(
            'requiredif',
            ['dependentproperty', 'targetvalue'],
            function (options) {
                options.rules['requiredif'] = {
                    dependentproperty: options.params['dependentproperty'],
                    targetvalue: options.params['targetvalue']
                };
                options.messages['requiredif'] = options.message;
            });



        }(jQuery));

        My model class is:

              public bool Subscribes { get; set; }


                    [RequiredIf("Subscribes", true, ErrorMessage = "You must enter EmailAddress")]

                    public string Email { get; set; }

我的观点是:

    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.requiredif.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

  <div>
            @Html.CheckBoxFor(x => x.Subscribes)
        </div>
        <div>
            @Html.LabelFor(x => x.Email)
        </div>
        <div >
            @Html.TextBoxFor(x => x.Email)
            @Html.ValidationMessageFor(model =>model.Email)

        </div>

1 个答案:

答案 0 :(得分:0)

&#13;
&#13;
<script type="text/javascript">
        function IsValidEmail(email) {
            var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
            return expr.test(email);
        };
        function ValidateEmail() {
            var email = document.getElementById("txtEmail").value;
            if (!IsValidEmail(email)) {
                alert("Invalid email address.");
            }
            else {
                alert("Valid email address.");
            }
        }
    </script>
&#13;
&#13;
&#13;