7

給定一個視圖模型,看起來像這樣:如何在客戶端上將自定義ValidationAttribute呈現爲'data-val-xx'屬性?

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實現這一目標?

E.g.我是否需要在我的自定義驗證器上添加一些特殊屬性?或註冊它的地方?

回答

7

那麼,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驗證有很多樂趣。 :)

相關問題