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");



最後に理解する必要があるのは、via を使用して設定されたエラー メッセージを渡す方法WithMessage()です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

http://fluentvalidation.codeplex.com/discussions/253505で Jeremy Skinner (Fluent Validation の作成者) とこれを行う方法について話し合っています。

彼は親切にも完全な例を書いてくれました。


更新
ここに私たちが思いついたコードがあります:

まず、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

ちょっと話が逸れますが、参考になれば。正規表現は非常に強力です。すべてのルールを 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 に答える