2

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

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

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

我发现的几乎所有解决方案都使用 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;}
4

3 回答 3

2

最后,我根据这篇博文编写了自己的 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;
});

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

        [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# 代码的作用基本相同。可以在我引用的博文中找到有关所有功能的详细说明

于 2013-04-16T11:17:46.147 回答
0

It seems like you want a "required if" validation attribute. I would check out http://foolproof.codeplex.com/ - it has an implementation that you can use like so (lifted directly from the project's site):

private class Person
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public bool Married { get; set; }

    [RequiredIfTrue("Married")]
    public string MaidenName { get; set; }
}
于 2013-04-16T08:30:19.520 回答
0

看看这个,我自己没用过,不过好像很适合你的需求http://foolproof.codeplex.com/workitem/18974

他们有一个看起来像这样的例子:

[RequiredIf("Country", Operator.RegExMatch, "(1033|4105)", ErrorMessage = "{0} is required")]
public string State { get; set; }

[Required(ErrorMessage = "{0} is required")]
public int Country { get; set; }
于 2013-04-16T09:13:28.237 回答