asp.net-mvc - 传递错误消息以进行客户端验证

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



我需要弄清楚的最后一件事是如何通过 GetClientValidationRules() 传递使用 WithMessage() 设置的错误消息,以便它最终出现在“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 源代码,但无法弄清楚。有人有什么想法吗?

最佳答案

我一直在与 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));
    }
}


验证器使用的接口(interface)

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 连接 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));

关于asp.net-mvc - 传递错误消息以进行客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5626739/

相关文章:

asp.net-mvc-3 - vs12 不再支持 CopyAllFilesToSingleFolderForPackageDependsOn

asp.net-mvc-3 - 如何使用 FluentValidation.TestHelper 使用 When() 条件对子验证器进行单元测试

c# - ServiceStack FluentValidation 中的自定义响应 DTO

asp.net-mvc - model.isvalid mvc servicestack 流畅验证

asp.net-mvc - 为什么使用 MVC post 来注销?

sql-server - 无法从 diff Web 角色中的本地数据库获取数据

mysql - ASP.NET - 无效的对象名称 'dbo.ForumSections'

c# - 用于动态 View 数据/表单的 ASP.Net MVC 编辑器模板

sql-server - EFCodeFirst 和 SqlCe4 的唯一约束

asp.net-mvc - 在 Web api 和类库中使用 unity DI