问题描述
我具有以下自定义验证属性,该属性是从StringLengthAttribute派生的:
I have the following custom validation attribute, which derives from 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属性却会生成.
The only purpose of this custom attribute is to localize the 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?
推荐答案
如果查看DataAnnotationsModelValidatorProvider的源代码,您会在BuildAttributeFactoriesDictionary方法中看到注册了特定类型的属性以进行客户端验证-您已经创建了一种新类型,因此没有客户端验证.
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.
值得庆幸的是,它还有一个公共方法来添加您自己的适配器,并且在您提供的简单情况下易于使用:
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) };
}
}
然后您需要像下面这样在Global.asax.cs的Application_Start方法中注册它:
You then need to register this in the Application_Start method in Global.asax.cs like so:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof (MyStringLengthAttribute), typeof (MyStringLengthAdapter));
这篇关于自定义StringLength验证属性的客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!