asp.net-mvc - MVC 禁用特定验证器的不引人注目的验证

标签 asp.net-mvc jquery-validate unobtrusive-validation

我目前正在构建一个 MVC4 项目,该项目通过数据注释使用不显眼的验证。

我有一个特定字段“邮政编码”,它既是[必填],又附加了一个[正则表达式]验证器。 问题是,只有选择特定国家/地区时才应验证此正则表达式。 (该国家/地区将成为默认值,我们可以假设几乎在所有情况下都会使用该值)

现在我需要某种方法来在选择不同的国家/地区时禁用此正则表达式验证,同时保持所需的验证器处于事件状态。

我发现的几乎所有解决方案都使用 jQuery.validator.defaults.ignore 过滤器,但这会禁用该项目上的两个验证器。

关于如何最好地解决这个问题有什么想法吗?

编辑:小代码片段以显示其工作原理。

[Required]
[RegularExpression("^[1-9]\\d{3} ?[a-zA-Z]{2}$"] //Should only be verified if Country == "The Netherlands"
string PostalCode{get;set;}

[Required]
string Country {get;set;}

最佳答案

最后我根据这篇博文编写了自己的ValidationAttribute:http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/ 这是一个优雅的解决方案,所需的工作量比我预期的要少。

编辑:根据要求,我提供了我自己创建的解决方案:

// DependentRegularExpressionAttribute.cs
    /// <summary>
/// Only performs a regular expression validation if a specified other property meets a validation requirement
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DependentRegularExpressionAttribute : ValidationAttribute, IClientValidatable
{
    private readonly Regex _regex;
    private readonly string _otherPropertyName;
    private readonly Regex _otherPropertyRegex;

    public DependentRegularExpressionAttribute(string regex, string otherPropertyName, string otherPropertyRegex)
    {
        _regex = new Regex(regex);
        _otherPropertyName = otherPropertyName;
        _otherPropertyRegex = new Regex(otherPropertyRegex);
    }

    /// <summary>
    /// Format the error message filling in the name of the property to validate and the reference one.
    /// </summary>
    /// <param name="name">The name of the property to validate</param>
    /// <returns>The formatted error message</returns>
    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, _regex, _otherPropertyName, _otherPropertyRegex);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var validationResult = ValidationResult.Success;

        if (value == null || String.IsNullOrEmpty(value as string))
            return validationResult;

        // Using reflection we can get a reference to the other property
        var otherPropertyInfo = validationContext.ObjectType.GetProperty(_otherPropertyName);
        var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
        if (otherPropertyValue == null || String.IsNullOrEmpty(otherPropertyValue as string))
            return validationResult;
        if (_otherPropertyRegex.IsMatch(otherPropertyValue.ToString()))
        {
            if (!_regex.IsMatch(value.ToString()))
                validationResult = new ValidationResult(ErrorMessage);
        }


        return validationResult;
    }


    #region IClientValidatable Members

    /// <summary>
    ///  
    /// </summary>
    /// <param name="metadata"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        string errorMessage = FormatErrorMessage(metadata.DisplayName ?? metadata.PropertyName);

        // The value we set here are needed by the jQuery adapter
        var dependentRegexRule = new ModelClientValidationRule
        {
            ErrorMessage = errorMessage,
            ValidationType = "dependentregex"
        };
        //"otherpropertyname" is the name of the jQuery parameter for the adapter, must be LOWERCASE!
        dependentRegexRule.ValidationParameters.Add("otherpropertyname", _otherPropertyName);
        dependentRegexRule.ValidationParameters.Add("regex", _regex);
        dependentRegexRule.ValidationParameters.Add("otherpropertyregex", _otherPropertyRegex);

        yield return dependentRegexRule;
    }

    #endregion

}


    // customvalidation.js
    $.validator.addMethod("dependentregex", function (value, element, params) {
    var regex = new RegExp(params[0]);
    var otherElement = document.getElementById(params[1]);
    var otherElementRegex = new RegExp(params[2]);

    if (!value || !otherElement.value)
        return true;

    if (otherElementRegex.test(otherElement.value)) {
        if (!regex.test(element.value))
            return false;
    }
    return true;
});

$.validator.unobtrusive.adapters.add("dependentregex", ["regex", "otherpropertyname", "otherpropertyregex"], function(options) {
    options.rules["dependentregex"] = [options.params.regex,
        options.params.otherpropertyname,
        options.params.otherpropertyregex];
    options.messages["dependentregex"] = options.message;
});

在我的 View 模型中,我执行以下操作:

        [Display(Name = "Customer_PostalCode", ResourceType = typeof(Resources.DisplayNames))]
    [DependentRegularExpression("^[1-9]\\d{3} ?[a-zA-Z]{2}$", "CorrespondenceCountry", "Nederland", ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "Customer_PostalCode")] //"Nederland" is a regular expression in this case
    [Required(ErrorMessageResourceType = typeof(Resources.Validation), ErrorMessageResourceName = "Shared_RequiredField")]
    public string CorrespondenceZipCode { get; set; }

最后,customvalidation.js 方法基本上执行与 C# 代码完全相同的操作。有关一切功能的详细说明可以在我引用的博文中找到

关于asp.net-mvc - MVC 禁用特定验证器的不引人注目的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16032042/

相关文章:

jquery-mobile - asp.net mvc TextAreaFor 未被验证为必填字段

javascript - RadioButton 不访问搜索使用 Jquery Ajax

asp.net-mvc - 当没有数据时如何隐藏 MVC View 中的表?

html - 如何使用@RenderPage 内嵌 CSS 内容 - MVC Razor

javascript - 如何添加打卡时间和实际时间

javascript - jQuery Textarea 验证不起作用

javascript - 使用 jQuery 在选择列表上进行验证

javascript - 如何将 onclick 事件添加到 Razor View 中的单选按钮

asp.net-mvc-3 - 如何进行不显眼的验证以清除电子邮件输入所需的验证?

c# - 自定义不显眼的日期验证器