c# – 自定义StringLength验证属性的客户端验证
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 自定义StringLength验证属性的客户端验证,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1643字,纯文字阅读大概需要3分钟。
内容图文
![c# – 自定义StringLength验证属性的客户端验证](/upload/InfoBanner/zyjiaocheng/787/1c233401ec984d0f9cf5fa337ce83c71.jpg)
我有以下自定义验证属性,它派生自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));
内容总结
以上是互联网集市为您收集整理的c# – 自定义StringLength验证属性的客户端验证全部内容,希望文章能够帮你解决c# – 自定义StringLength验证属性的客户端验证所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。