【问题标题】:Multifield required validation is not working in client side in MVC 5?在 MVC 5 的客户端中,多字段所需的验证不起作用?
【发布时间】:2016-09-08 17:41:03
【问题描述】:

我曾经使用此链接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>
    }

【问题讨论】:

  • 什么不工作 - 客户端或服务器端验证或两者兼而有之?您已经实现了IClientValidatable,但没有显示您的脚本以将规则添加到$.validator,这是客户端验证所必需的
  • 服务器端和客户端都不起作用。另外我不知道我需要在 javascript 中进行的#.validator 更改
  • 要了解客户端验证所需的内容,请参阅The Complete Guide To Validation In ASP.NET MVC 3 - Part 2。但它不是很清楚你想做什么。如果您希望在 PhoneNumber 上具有必需的验证属性,同时确保 AreaCode 具有值,那么您应该将一个属性仅应用于 PhoneNumber,并且该属性接受另一个属性的 nae 参数。跨度>
  • 应该是return ValidationResult.Success;(不是return null;
  • 我也添加了 javascript 代码...您能找到问题并立即解决吗

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


【解决方案1】:

您链接到的答案和您所基于的代码没有多大意义。将验证属性应用于您的 AreaCode 属性而不包括关联的 @Html.ValidationMessageFor() 是没有意义的。

如果您想要与PhoneNumber 关联的验证消息,如果它为空,则会显示请输入电话号码错误,并显示请同时输入区号 em> 如果它不为空,但 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>

【讨论】:

    【解决方案2】:

    如果我没记错的话,MultiFieldRequired 会在 类名 上方使用,这在前面的 stackoverflow 链接中进行了说明: MVC3 Validating Multiple Fields As A Single Property

    您也可以在模型中尝试以下方法。也 添加命名空间

    型号

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

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-05
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2013-01-09
      • 2014-03-25
      相关资源
      最近更新 更多