2010-05-28 82 views
1

我有一個必需的屬性與資源使用:ASP.NET MVC 2:數據DataAnnotations驗證是慣例

public class ArticleInput : InputBase 
{ 
    [Required(ErrorMessageResourceType = typeof(ArticleResources), ErrorMessageResourceName = "Body_Validation_Required")] 
    public string Body { get; set; } 
} 

我想指定資源成爲慣例,這樣的:

public class ArticleInput : InputBase 
{ 
    [Required2] 
    public string Body { get; set; } 
} 

基本上,Required2實施基於此數據的值:

ErrorMessageResourceType = typeof(ClassNameWithoutInput + Resources); // ArticleResources 
ErrorMessageResourceName = typeof(PropertyName + "_Validation_Required"); // Body_Validation_Required 

Is there任何方式來實現這樣的事情?也許我需要實施一個新的ValidationAttribute

回答

1

我不認爲這是可能的,或者至少,如果不爲該屬性提供自定義適配器,也不可能做到這一點。您在屬性的構造函數中沒有任何方式來訪問該屬性應用於的方法/屬性。沒有這些,你無法獲得類型或屬性名稱信息。

如果您爲屬性創建了適配器,然後使用DataAnnotationsModelValidatorProvider註冊它,那麼在GetClientValidationRules中,您將有權訪問ControllerContext和模型元數據。從中您可能能夠派生出正確的資源類型和名稱,然後查找正確的錯誤消息並將其添加到屬性的客戶端驗證規則中。

public class Required2AttributeAdapter 
    : DataAnnotationsModelValidator<Required2Attribute> 
{ 
    public Required2AttributeAdapter(ModelMetadata metadata, 
             ControllerContext context, 
             Required2Attribute attribute) 
     : base(metadata, context, attribute) 
    { 
    } 

    public override IEnumerable<ModelClientValidationRule> 
     GetClientValidationRules() 
    { 
     // use this.ControllerContext and this.Metadata to find 
     // the correct error message from the correct set of resources 
     // 
     return new[] { 
      new ModelClientValidationRequiredRule(localizedErrorMessage) 
     }; 
    } 
} 

然後在的global.asax.cs

DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(Required2Attribute), 
    typeof(Required2AttributeAdapter) 
); 
+0

我可以用一個適配器與任何驗證屬性?只需使用'DataAnnotationsModelValidator '? – stacker 2010-05-28 21:05:13

+0

@stacker - 現有的屬性已經註冊了適配器。內部字典的確切類型也是如此,所以我認爲您需要爲每個屬性類型配備一個適配器。 – tvanfosson 2010-05-28 21:25:44