多场所需的验证在MVC 5的客户端不起作用?

时间:2016-09-05 07:00:28

标签: c# asp.net-mvc-5

我曾经使用此链接MVC3 Validating Multiple Fields As A Single Property

实现多字段必需的验证

但它在我的结尾不起作用。

以下是我使用的代码。

的Javascript

    $.validator.addMethod('multifield', function (value, element, params) {
    var properties = params.propertyname.split(',');
    var isValid = false;
    var count = 0;
    for (var i = 0; i < properties.length; i++) {
        var property = properties[i];
        if ($('#' + property).val() != "") {
            count++;
        }
    }
    if (properties.length == count) {
        isValid = true;
    }
    return isValid;
}, '');

$.validator.unobtrusive.adapters.add('multifield', ['propertyname'], function (options) {
    options.rules['multifield'] = options.params;
    options.messages['multifield'] = options.message;
}
);

  public class Customer
    {
       public string AreaCode { get; set; }
      [MultiFieldRequired(new string[2] { "AreaCode", "PhoneNumber" }, ErrorMessage = "Please enter a phone number")]
       public string PhoneNumber { get; set; }
    }

    public class MultiFieldRequiredAttribute : ValidationAttribute, IClientValidatable
{
    string propertyName;
    private readonly string[] _fields;

    public MultiFieldRequiredAttribute(string[] fields)
    {
        _fields = fields;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach (string field in _fields)
        {
            propertyName = field;
            PropertyInfo property = validationContext.ObjectType.GetProperty(field);
            if (property == null)
                return new ValidationResult(string.Format("Property '{0}' is undefined.", field));

            var fieldValue = property.GetValue(validationContext.ObjectInstance, null);

            if (fieldValue == null || String.IsNullOrEmpty(fieldValue.ToString()))
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }

        return ValidationResult.Success;
    }

     public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        // The value we set here are needed by the jQuery adapter
        ModelClientValidationRule multifield = new ModelClientValidationRule();
        multifield.ErrorMessage = this.ErrorMessage;
        multifield.ValidationType = "multifield"; // This is the name the jQuery validator will use
        //"otherpropertyname" is the name of the jQuery parameter for the adapter, must be LOWERCASE!
        multifield.ValidationParameters.Add("propertyname", string.Join(",", _fields));

        yield return multifield;
    }
}

查看

@using (Html.BeginForm("Add", "Home", FormMethod.Post, new { @class = "form-inline" }))
    {


    <div class="editor-label">
        @Html.LabelFor(model => model.AreaCode)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.AreaCode)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.PhoneNumber)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.PhoneNumber)
        @Html.ValidationMessageFor(model => model.PhoneNumber)
    </div>
          <button type="submit" tabindex="19" class="form-control btn btn-primary" style="float: right; margin-left: 8px; margin-right: 10px;">Submit</button>
    }

2 个答案:

答案 0 :(得分:1)

您链接到的答案以及基于它的代码并没有多大意义。将验证属性应用于AreaCode属性而不包含关联的@Html.ValidationMessageFor()是毫无意义的。

如果您希望与PhoneNumber相关联的验证邮件显示请输入电话号码错误(如果它已空),并显示请同时输入区号如果它不为空但AreaCode值为,则需要一个仅应用于PhoneNumber属性的属性,该属性需要接受一个参数其他财产名称。

模型

public string AreaCode { get; set; }
[Required(ErrorMessage = "Please enter a phone number")]
[RequiredWith("AreaCode", ErrorMessage = "Please also enter an Area Code")]
public string PhoneNumber { get; set; }

验证属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RequiredWithAttribute : ValidationAttribute, IClientValidatable
{
    private const string _DefaultErrorMessage = "The {0} is also required.";
    private readonly string _OtherPropertyName;

    public RequiredWithAttribute(string otherPropertyName)
    {
        if (string.IsNullOrEmpty(otherPropertyName))
        {
            throw new ArgumentNullException("otherPropertyName");
        }
        _OtherPropertyName = otherPropertyName;
        ErrorMessage = _DefaultErrorMessage;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_OtherPropertyName);
            var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
            if (otherPropertyValue == null)
            {
                return new ValidationResult(string.Format(ErrorMessageString, _OtherPropertyName));
            }
        }
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(_OtherPropertyName),
            ValidationType = "requiredwith",
        };
        rule.ValidationParameters.Add("dependentproperty", _OtherPropertyName);
        yield return rule;
    }
}

并添加以下脚本

<script type="text/javascript">
    // General function to get the associated element
    myValidation = {
        getDependantProperyID: function (validationElement, dependantProperty) {
            if (document.getElementById(dependantProperty)) {
                return dependantProperty;
            }
            var name = validationElement.name;
            var index = name.lastIndexOf(".") + 1;
            dependantProperty = (name.substr(0, index) + dependantProperty).replace(/[\.\[\]]/g, "_");
            if (document.getElementById(dependantProperty)) {
                return dependantProperty;
            }
            return null;
        }
    }

    $.validator.addMethod("requiredwith", function (value, element, params) {
        var dependantControl = $('#' + params.dependentproperty);
        return dependantControl.val() !== '';
    });

    $.validator.unobtrusive.adapters.add("requiredwith", ["dependentproperty"], function (options) {
        var element = options.element;
        var dependentproperty = options.params.dependentproperty;
        dependentproperty = myValidation.getDependantProperyID(element, dependentproperty);
        options.rules['requiredwith'] = {
            dependentproperty: dependentproperty
        };
        options.messages['requiredwith'] = options.message;
    });

</script>

答案 1 :(得分:0)

如果我没错,则在类名之上使用MultiFieldRequired,这在前面的 stackoverflow 链接中有说明: jsonpage

您也可以在模型中尝试以下方法。此外

中添加命名空间
  

模型

=====================

using System.Web.Mvc; 

=====================

 public class Customer
    {
        //...other fields here
         [Remote("ValidateAreaPhoneNumber","Home",AdditionalFields="PhoneNumber",ErrorMessage="Please enter a phone number")]

        public string AreaCode { get; set; }

        public string PhoneNumber { get; set; }
    }

您可以编写名为

的方法
  

ValidateAreaPhoneNumber

在你的

  

家庭控制器

如下:

public JsonResult ValidateAreaPhoneNumber(string PhoneNumber)
{

    //True:False--- action that implement to check PhoneNumber uniqueness

      return false;//Always return false to display error message
}