我有以下自定义验证属性,它派生自 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)方法来添加您自己的适配器,并且在您给出的简单情况下很容易使用:
首先,您需要一个适配器来提供客户端验证规则:
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));
关于c# - 自定义 StringLength 验证属性的客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28173753/