简体   繁体   English

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

[英]Client-side validation for custom StringLength validation attribute

I have the following custom validation attribute, which derives from StringLengthAttribute: 我有以下自定义验证属性,它派生自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());
    }
}

The only purpose of this custom attribute is to localize the ErrorMessage. 此自定义属性的唯一用途是本地化ErrorMessage。 The problem is, when I use this in my models it does not generate any client-side validation, but the standard StringLength attribute does. 问题是,当我在模型中使用它时,它不会生成任何客户端验证,但标准的StringLength属性会生成。

I don't see how my attribute differs in any way - since it derives from the StringLength attribute I shouldn't have to implement any additional functionality to get client side validation working? 我没有看到我的属性如何以任何方式有所不同 - 因为它派生自StringLength属性,我不应该实现任何其他功能来使客户端验证工作?

If you look at the source code for DataAnnotationsModelValidatorProvider, you'll see in the method BuildAttributeFactoriesDictionary that specific types of attributes are registered for client side validation - you have created a new type, hence no client side validation. 如果查看DataAnnotationsModelValidatorProvider的源代码,您将在方法BuildAttributeFactoriesDictionary中看到为客户端验证注册了特定类型的属性 - 您创建了一个新类型,因此没有客户端验证。

Thankfully, this also has a public method to add your own adapter and is easy to use in the simple case you give: 值得庆幸的是,这也有一个公共方法来添加自己的适配器,并且在您给出的简单情况下易于使用:

Firstly, you need an adapter that will provide the client validation rules: 首先,您需要一个提供客户端验证规则的适配器:

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

You then need to register this in the Application_Start method in Global.asax.cs like so: 然后,您需要在Global.asax.cs中的Application_Start方法中注册它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM