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

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

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

和这样的观点(在这里剃须刀语法):

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

我得到以下标记:

<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实现这一目标?

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

有帮助吗?

解决方案

好吧,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 };
    }
}

(“验证类型”设置 必须 为此工作要较低,因为这是将其用作HTML5属性 - 'data-val-custom'的后修饰。)。

然后,我要做的就是在application_start上注册它。

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

期待HTML5验证的乐趣。 :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top