【问题标题】:How can I have a custom ValidationAttribute rendered as a 'data-val-xx' attribute on the client-side?如何在客户端将自定义 ValidationAttribute 呈现为“da​​ta-val-xx”属性?
【发布时间】:2011-05-06 11:14:07
【问题描述】:

给定一个看起来像这样的 ViewModel:

public class Login {
    [Required]
    public string Username { get; set; }

    [Required, CustomValidator]
    public string Password { get; set; }
}

还有这样的视图(此处为 Razor 语法):

@Html.TextBoxFor(f => f.Password)

我得到以下标记:

<input type="text"
       value="" 
       data-val-required="This field is required." />

但是我希望它也为我的 custom 验证器包含一个“data-”属性。

我想要这样的东西:

<input type="text" 
       value="" 
       data-val-required="This field is required."
       data-val-customvalidator="XYZ" />

如何使用 ASP.NET MVC 3.0 实现这一点?

例如我需要在我的自定义验证器上添加一些特殊属性吗?还是在某个地方注册?

【问题讨论】:

    标签: asp.net-mvc-3 validationattribute unobtrusive-validation


    【解决方案1】:

    嗯,MSDN 救了我(就像它经常做的那样)。

    http://msdn.microsoft.com/en-us/library/ff398048.aspx

    所以首先我必须为我的验证属性创建一个适配器:

    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 };
        }
    }
    

    ('ValidationType' 设置 必须 为小写才能使其工作,因为这是将用作 HTML5 属性的后修复 - 'data-val-custom'。 )

    然后我需要做的就是在 Application_Start 上注册它。

    DataAnnotationsModelValidatorProvider.RegisterAdapter(
        typeof(EmailAttribute),
        typeof(EmailAttributeAdapter));
    

    期待 HTML5 验证带来更多乐趣。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-28
      • 2015-06-25
      • 1970-01-01
      • 2014-03-27
      • 2011-09-09
      • 1970-01-01
      • 2023-04-01
      • 2018-05-09
      相关资源
      最近更新 更多