2012-12-14 11 views
6

FluentValidation 전화 규칙 집합 및 공통 규칙나는 다음과 같은 클래스가

public class ValidProjectHeader : AbstractValidator<Projects.ProjectHeader> 
    { 
     public ValidProjectHeader() 
     { 

      RuleFor(x => x.LobId).Must(ValidateLOBIDExists); 
      RuleFor(x => x.CreatedByUserId).NotEmpty(); 
      RuleFor(x => x.ProjectManagerId).NotEmpty(); 
      RuleFor(x => x.ProjectName).NotEmpty(); 
      RuleFor(x => x.SalesRepId).NotEmpty(); 
      RuleFor(x => x.DeliveryDate).NotEmpty(); 
      RuleFor(x => x.ProjectStatusId).NotEmpty(); 
      RuleFor(x => x.DeptartmentId).NotEmpty(); 
      RuleFor(x => x.CustomerId).NotEmpty(); 

      RuleSet("Insert",() => 
      { 
       RuleFor(x => x.ProjectLines).Must(ValidateProjectLines).SetCollectionValidator(new ValidProjectLine()); 
      }); 
      RuleSet("Update",() => 
      { 
       RuleFor(x => x.ProjectLines).SetCollectionValidator(new ValidProjectLine()); 
      }); 


     } 

와 내가 뭘하려고하면 rulset로 확인 전화를하지만 나는 또한 내가 전화 할 때 "일반적인"규칙을 반환하려면 RuleSet을 사용한 유효성 검사. 내가 회원 ruleSet와 방법 CallValidation를 호출 할 수 있지만, 그것은 또한 "일반"규칙을 호출되지

public abstract class BaseValidator 
    { 
     private List<ValidationFailure> _errors; 
     public bool IsValid { get; protected set; } 
     public List<ValidationFailure> Errors 
     { 
      get { return _errors; } 
      protected set { _errors = value; } 
     } 
     public virtual bool CallValidation() 
     { 
      Errors = new List<ValidationFailure>(); 
      ValidatorAttribute val = this.GetType().GetCustomAttributes(typeof(ValidatorAttribute), true)[0] as ValidatorAttribute; 
      IValidator validator = Activator.CreateInstance(val.ValidatorType) as IValidator; 
      FluentValidation.Results.ValidationResult result = validator.Validate(this); 
      IsValid = result.IsValid; 
      Errors = result.Errors.ToList(); 
      return result.IsValid; 
     } 

     public virtual bool CallValidation(string ruleSet) 
     { 
      Errors = new List<ValidationFailure>(); 
      ValidatorAttribute val = this.GetType().GetCustomAttributes(typeof(ValidatorAttribute), true)[0] as ValidatorAttribute; 
      IValidator validator = Activator.CreateInstance(val.ValidatorType) as IValidator; 
      FluentValidation.Results.ValidationResult result = validator.Validate(new FluentValidation.ValidationContext(this, new PropertyChain(), new RulesetValidatorSelector(ruleSet))); 
      IsValid = result.IsValid; 
      Errors = result.Errors.ToList(); 
      return result.IsValid; 
     } 

     public BaseValidator() 
     { 
      Errors = new List<ValidationFailure>(); 
     } 
    } 

을 다음과 같이

내가 유효성 검사를 호출있는 코드이다.

나는이 규칙을 실행하기위한 "공통"규칙 집합을 만들 수 있지만이 경우에는 항상 공통 규칙 집합을 사용하여 유효성 검사를 호출해야한다는 것을 알고 있습니다.

규칙 집합을 호출하고 공통 규칙을 호출 할 수있는 방법이 있습니까?

답변

3

나는

public virtual bool CallValidation(string ruleSet) 
     { 
      Errors = new List<ValidationFailure>(); 
      ValidatorAttribute val = this.GetType().GetCustomAttributes(typeof(ValidatorAttribute), true)[0] as ValidatorAttribute; 
      IValidator validator = Activator.CreateInstance(val.ValidatorType) as IValidator; 
      FluentValidation.Results.ValidationResult result = validator.Validate(new FluentValidation.ValidationContext(this, new PropertyChain(), new RulesetValidatorSelector(ruleSet))); 
      FluentValidation.Results.ValidationResult resultCommon = validator.Validate(this); 
      IsValid = (result.IsValid && resultCommon.IsValid); 
      Errors = result.Errors.Union(resultCommon.Errors).ToList(); 
      return IsValid; 
     } 
7

대신이 할 수있는 다음과 같이 인 CallValidation(string ruleSet) 방법에 두 번째 validator.Validate 를 추가하여 한 가지 방법 발견 : 당신의 Validator 클래스에서

FluentValidation.Results.ValidationResult resultCommon = validator.Validate(parameter, Ruleset : "default, Insert"); 
+0

이 옵션은 git 소스 코드에 적어도 2009 년 이후로 존재하지 않는 것으로 보입니다. 문서가 올바르지 않기 때문에이 부분에서 나를 이끌었습니다. – john

+0

큰 충고! FluentValidation 6.2.1에서는 RuleSet 인수의 대소 문자가 다릅니다 : "Ruleset :"대신 "ruleSet :". 예 : validator.Validate (obj, ruleSet : "default, Insert"); –

6

을 항상 적용해야하는 모든 "공통"규칙을 포함하는 메소드를 작성하십시오. 지금 당신은 당신은 당신의 컨트롤러에서 작업에 대한 규칙 집합을 정의하는 예

규칙 집합 외부에서 "생성"규칙 집합에서이 방법을

public class MyEntityValidator : AbstractValidator<MyEntity> 
{ 
    public MyEntityValidator() 
    { 
     RuleSet("Create",() => 
      { 
       RuleFor(x => x.Email).EmailAddress(); 
       ExecuteCommonRules(); 
      }); 

     ExecuteCommonRules(); 
    } 

    /// <summary> 
    /// Rules that should be applied at all times 
    /// </summary> 
    private void ExecuteCommonRules() 
    { 
     RuleFor(x => x.Name).NotEmpty(); 
     RuleFor(x => x.City).NotEmpty(); 
    } 
} 

    • 를 호출 할 수 있습니다

      [HttpPost] 
      public ActionResult Create([CustomizeValidator(RuleSet = "Create")] MyEntity model) 
      

      Create Action에 대한 요청은 RuleSet Create를 사용하여 유효성을 검사합니다. 다른 모든 액션은 컨트롤러에서 ExecuteCommonRules에 대한 호출을 사용합니다.

  • 관련 문제