[英]Client-side validation for custom StringLength validation attribute
我有以下自定義驗證屬性,它派生自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屬性,我不應該實現任何其他功能來使客戶端驗證工作?
如果查看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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.