2012-09-13 88 views
0

兩個驗證我有以下的驗證器類:流利的驗證 - 組中的一個自定義的驗證

public class FranchiseInfoValidator : AbstractValidator<FranchiseInfo> 
    { 
     public FranchiseInfoValidator() 
     { 
      RuleFor(franchiseInfo => franchiseInfo.FolderName).NotEmpty().Matches("^[a-zA-Z0-9_.:-]+$").WithMessage("Invalid characters"); 
      RuleFor(franchiseInfo => franchiseInfo.ExeIconName).NotEmpty().Matches("^[a-zA-Z0-9_.:-]+$").WithMessage("Invalid characters"); 
      RuleFor(franchiseInfo => franchiseInfo.FullName).NotEmpty().Matches("^[a-zA-Z0-9_.:-]+$").WithMessage("Invalid characters"); 
      RuleFor(franchiseInfo => franchiseInfo.ShortName).NotEmpty().Matches("^[a-zA-Z0-9_.:-]+$").WithMessage("Invalid characters");   
    } 

NotEmpty()Matches("^[a-zA-Z0-9_.:-]+$").WithMessage("Invalid characters")驗證與自定義消息是對所有性質是相同的。是否有可能將其組中的一個自定義的驗證,然後寫些這樣的:

RuleFor(franchiseInfo => franchiseInfo.FolderName).SetValidator(new CustomValidator()); 

我已經做了一些自定義的驗證,但不是在這種情況下。這可能嗎?我在文檔中找不到這樣的例子。此外,我不知道這是否可以做到泛型,所以如果我有另一個具有屬性的驗證器類來應用相同的自定義驗證器?謝謝。

回答

3

是的,它應該有類似的東西

public class MyCustomValidator : PropertyValidator 
    { 

     public MyCustomValidator() 
      : base("Property {PropertyName} has invalid characters.") 
     { 
     } 

     protected override bool IsValid(PropertyValidatorContext context) 
     { 
      var element = context.PropertyValue as string; 
      return !string.IsNullOrEmpty(element) && Regex.IsMatch(element, "^[a-zA-Z0-9_.:-]+$"); 
     } 
    } 

使用工作: 與您的代碼,或者創建自己的擴展

public static class MyValidatorExtensions { 
    public static IRuleBuilderOptions<T, string> CheckIfNullAndMatches<T>(this IRuleBuilder<T, string> ruleBuilder) { 
     return ruleBuilder.SetValidator(new MyCustomValidator<TElement>()); 
    } 
} 

然後用法是

RuleFor(franchiseInfo => franchiseInfo.FolderName).CheckIfNullAndMatches(); 

如果你需要一個更通用的驗證器,你也可以有一個正則表達式作爲參數。

doc here