传递错误消息以进行客户端验证

时间:2011-04-11 19:53:40

标签: asp.net-mvc asp.net-mvc-3 fluentvalidation

由于无法使用多个正则表达式模式验证属性(使用不显眼的客户端验证)(因为验证类型必须是唯一的),我决定扩展FluentValidation,以便我可以执行以下操作。

RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required")
                    .Length(3, 20).WithMessage("Name must contain between 3 and 20 characters")
                    .Match(@"^[A-Z]").WithMessage("Name has to start with an uppercase letter")
                    .Match(@"^[a-zA-Z0-9_\-\.]*$").WithMessage("Name can only contain: a-z 0-9 _ - .")
                    .Match(@"[a-z0-9]$").WithMessage("Name has to end with a lowercase letter or digit")
                    .NotMatch(@"[_\-\.]{2,}").WithMessage("Name cannot contain consecutive non-alphanumeric characters");



我需要弄清楚的最后一件事是如何传递使用WithMessage()通过GetClientValidationRules()设置的errormessage,因此它最终出现在输入元素的“data-val-customregex [SOMEFANCYSTRINGHERETOMAKEITUNIQUE]”属性中

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
    var rule = new ModelClientValidationRule();
    rule.ErrorMessage = [INSERT ERRORMESSAGE HERE];
    rule.ValidationType = "customregex" + StringFunctions.RandomLetters(6);
    rule.ValidationParameters.Add("pattern", pattern);

    yield return rule;
}


我一直在查看FluentValidation源代码,但无法弄明白。有人有任何想法吗?

2 个答案:

答案 0 :(得分:2)

我一直在与Jeremy Skinner(Fluent验证的创建者)讨论如何做到这一点 http://fluentvalidation.codeplex.com/discussions/253505

他很友好地写了一个完整的例子。


更新
以下是我们提出的代码:

首先是Match和NotMatch的扩展名。

public static class Extensions
{
    public static IRuleBuilderOptions<T, string> Match<T>(this IRuleBuilder<T, string> ruleBuilder, string expression)
    {
        return ruleBuilder.SetValidator(new MatchValidator(expression));
    }

    public static IRuleBuilderOptions<T, string> NotMatch<T>(this IRuleBuilder<T, string> ruleBuilder, string expression) {
        return ruleBuilder.SetValidator(new MatchValidator(expression, false));
    }
}


验证器的使用接口

public interface IMatchValidator : IPropertyValidator
{
    string Expression { get; }
    bool MustMatch { get; }
}


实际验证员:

public class MatchValidator : PropertyValidator, IMatchValidator
{
    string expression;
    bool mustMatch;

    public MatchValidator(string expression, bool mustMatch = true)
        : base(string.Format("The value {0} match with the given expression, while it {1}.", mustMatch ? "did not" : "did", mustMatch ? "should" : "should not"))
    {
        this.expression = expression;
        this.mustMatch = mustMatch;
    }

    protected override bool IsValid(PropertyValidatorContext context)
    {
        return context.PropertyValue == null ||
               context.PropertyValue.ToString() == string.Empty ||
               Regex.IsMatch(context.PropertyValue.ToString(), expression) == mustMatch;
    }

    public string Expression
    {
        get { return expression; }
    }

    public bool MustMatch {
        get { return mustMatch; }
    }
}


用于注册验证器的适配器:

public class MatchValidatorAdaptor : FluentValidationPropertyValidator
{
    public MatchValidatorAdaptor(ModelMetadata metadata, ControllerContext controllerContext, PropertyRule rule, IPropertyValidator validator)
        : base(metadata, controllerContext, rule, validator)
    {
    }

    IMatchValidator MatchValidator
    {
        get { return (IMatchValidator)Validator; }
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyDescription);
        string errorMessage = formatter.BuildMessage(Validator.ErrorMessageSource.GetString());
        yield return new ModelClientValidationMatchRule(MatchValidator.Expression, MatchValidator.MustMatch, errorMessage);
    }
}

最后神奇发生的地方:

public class ModelClientValidationMatchRule : ModelClientValidationRule
{
    public ModelClientValidationMatchRule(string expression, bool mustMatch, string errorMessage)
    {
        if (mustMatch)
            base.ValidationType = "match";
        else
            base.ValidationType = "notmatch";

        base.ValidationType += StringFunctions.RandomLetters(6);
        base.ErrorMessage = errorMessage;
        base.ValidationParameters.Add("expression", expression);
    }
}



更新2:
Javascript to wireup jQuery.validator:

(function ($) {
    function attachMatchValidator(name, mustMatch) {
        $.validator.addMethod(name, function (val, element, expression) {
            var rg = new RegExp(expression, "gi");
            return (rg.test(val) == mustMatch);
        });

        $.validator.unobtrusive.adapters.addSingleVal(name, "expression");
    }

    $("input[type=text]").each(function () {
        $.each(this.attributes, function (i, attribute) {
            if (attribute.name.length == 20 && attribute.name.substring(0, 14) == "data-val-match")
                attachMatchValidator(attribute.name.substring(9, 20), true);

            if (attribute.name.length == 23 && attribute.name.substring(0, 17) == "data-val-notmatch")
                attachMatchValidator(attribute.name.substring(9, 23), false);
        });
    });
} (jQuery));

答案 1 :(得分:1)

有点偏离主题,但也许有帮助。正则表达式非常强大,您是否考虑将所有规则组合在一个正则表达式中?我认为这就是为什么提供正则表达式验证的属性通常不允许每个属性有多个实例。

因此,对于您的示例,您的正则表达式将是:

"^[A-Z]([a-zA-Z0-9][_\-\.]{0,1}[a-zA-Z0-9]*)*[a-z0-9]$"

一个方便的地方来测试它:http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx