2

由于无法使用多个正则表达式模式(因为验证类型必须是唯一的)来验证属性(使用不显眼的客户端验证),我决定扩展 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()via设置的错误消息,GetClientValidationRules()因此它最终出现在输入元素的“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 源代码,但无法弄清楚。有人有什么想法吗?

4

2 回答 2

2

我一直在与 Jeremy Skinner(Fluent Validation 的创建者)在
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:
连接 jQuery.validator 的 Javascript:

(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));
于 2011-04-12T09:51:05.930 回答
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

于 2011-04-11T20:55:20.147 回答