怎样才可以有呈现为一个“数据-VAL-XX”在客户端属性自定义ValidationAttribute? [英] How can I have a custom ValidationAttribute rendered as a 'data-val-xx' attribute on the client-side?

查看:196
本文介绍了怎样才可以有呈现为一个“数据-VAL-XX”在客户端属性自定义ValidationAttribute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个视图模型,看起来像这样:

Given a ViewModel that looks like this:

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

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

和这样的(这里剃刀语法)视图:

And a View like this (Razor syntax here):

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

我收到以下标记:

I am getting the following markup:

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

不过,我想它也包括了数据 - 属性我的自定义的验证。

我想是这样的:

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

我如何与ASP.NET MVC 3.0实现这一目标?

How can I achieve this with ASP.NET MVC 3.0?

例如。我需要把一些特殊的属性在我的自定义验证?或地方注册呢?

E.g. Do I need to put some special attribute on my custom validator? Or register it somewhere?

推荐答案

好了,MSDN救了我(因为它往往如此)。

Well, MSDN saved me (as it often does).

<一个href=\"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 };
    }
}

(以下简称ValidationType设置的必须的是小写这个工作,因为这是将被用来作为一个HTML5属性后的修复 - 数据-VAL-自定义。 )

(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'.)

然后,所有我需要做的就是注册它的Application_Start。

Then all I need to do is register it on Application_Start.

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

期待很多的乐趣与HTML5验证。 :)

Looking forward to a lot of fun with HTML5 validation. :)

这篇关于怎样才可以有呈现为一个“数据-VAL-XX”在客户端属性自定义ValidationAttribute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆