[英]How can I have a custom ValidationAttribute rendered as a 'data-val-xx' attribute on the client-side?
Given a ViewModel that looks like this: 给定一个如下所示的ViewModel:
public class Login {
[Required]
public string Username { get; set; }
[Required, CustomValidator]
public string Password { get; set; }
}
And a View like this (Razor syntax here): 像这样的视图(Razor语法在这里):
@Html.TextBoxFor(f => f.Password)
I am getting the following markup: 我得到以下标记:
<input type="text"
value=""
data-val-required="This field is required." />
However I would like it to also include a 'data-' attribute for my custom validator. 但是我希望它还包含我的自定义验证器的'data-'属性。
I want something like this: 我想要这样的东西:
<input type="text"
value=""
data-val-required="This field is required."
data-val-customvalidator="XYZ" />
How can I achieve this with ASP.NET MVC 3.0? 如何使用ASP.NET MVC 3.0实现这一目标?
Eg Do I need to put some special attribute on my custom validator? 例如,我是否需要在自定义验证器上添加一些特殊属性? Or register it somewhere? 或者在某处注册?
Well, MSDN saved me (as it often does). 好吧,MSDN救了我(就像它经常那样)。
http://msdn.microsoft.com/en-us/library/ff398048.aspx http://msdn.microsoft.com/en-us/library/ff398048.aspx
So first I have to create an adapter for my validation attribute: 首先,我必须为我的验证属性创建一个适配器:
public class CustomAttributeAdapter : DataAnnotationsModelValidator<EmailAttribute>
{
public CustomAttributeAdapter(
ModelMetadata metadata,
ControllerContext context,
CustomAttribute attribute) :
base(metadata, context, attribute)
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
ModelClientValidationRule rule = new ModelClientValidationRule()
{
ErrorMessage = ErrorMessage,
ValidationType = "custom"
};
return new ModelClientValidationRule[] { rule };
}
}
(The 'ValidationType' setting must be lower-case for this to work, as this is the post-fix which will be used as an HTML5 attribute - 'data-val-custom'.) ('ValidationType'设置必须小写才能生效,因为这是将用作HTML5属性的后修复 - 'data-val-custom'。)
Then all I need to do is register it on Application_Start. 然后,我需要做的就是在Application_Start上注册它。
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(EmailAttribute),
typeof(EmailAttributeAdapter));
Looking forward to a lot of fun with HTML5 validation. 期待HTML5验证带来很多乐趣。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.