自定义StringLength验证属性的客户端验证

时间:2015-01-27 15:14:30

标签: c# asp.net-mvc validation

我有以下自定义验证属性,该属性派生自StringLengthAttribute:

public class StringLengthLocalizedAttribute : StringLengthAttribute
{
    public StringLengthLocalizedAttribute(int maximumLength) : base(maximumLength)
    {
        var translator = DependencyResolver.Current.GetService<ITranslator();
        var translatedValue = translator.Translate("MaxLengthTranslationKey", ErrorMessage);
        ErrorMessage = translatedValue.Replace("{MaxLength}", maximumLength.ToString());
    }
}

此自定义属性的唯一用途是本地化ErrorMessage。问题是,当我在模型中使用它时,它不会生成任何客户端验证,但标准的StringLength属性会生成。

我没有看到我的属性如何以任何方式存在差异 - 因为它源自StringLength属性我不应该实现任何其他功能来使客户端验证工作?

1 个答案:

答案 0 :(得分:3)

如果查看DataAnnotationsModelValidatorProvider的源代码,您将在方法BuildAttributeFactoriesDictionary中看到为客户端验证注册了特定类型的属性 - 您创建了一个新类型,因此没有客户端验证。

值得庆幸的是,这也有一个公共方法来添加您自己的适配器,并且在您给出的简单情况下易于使用:

首先,您需要一个提供客户端验证规则的适配器:

public class MyStringLengthAdapter : DataAnnotationsModelValidator<MyStringLengthAttribute>
{
    public MyStringLengthAdapter(ModelMetadata metadata, ControllerContext context, MyStringLengthAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return new[] { new ModelClientValidationStringLengthRule(ErrorMessage, Attribute.MinimumLength, Attribute.MaximumLength) };
    }
}

然后你需要在Global.asax.cs中的Application_Start方法中注册它,如下所示:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof (MyStringLengthAttribute), typeof (MyStringLengthAdapter));