c# - Conditionally validate collection -


public class prospectvalidator : abstractvalidator<prospect> {     public prospectvalidator()     {            rulefor(p => p.competitorproducts)             .notnull()             .when(p => !p.existingcustomer);          rulefor(p => p.competitorproducts.count)             .greaterthan(0)             .when(p => p.competitorproducts != null && !p.existingcustomer);     } } 

this validator checks if existingcustomer false competitorproducts not null , has @ least 1 element.

it works possible write 1 rule?

you have 2 options doing in single command, both bit tricky need validate inner property while validating encompassing class not null. both revolve around cascade property (see "setting cascade mode") stop validation on first error.

first, can use must validation. need specify withmessage i've done avoid getting generic "the specified condition not met 'competitor products'." error. may want override witherrorcode defaults predicate. note show on second validation error; first error still correctly return message property must not null.

rulefor(p => p.competitorproducts)   .cascade(cascademode.stoponfirstfailure)   .notnull()   .must(p => p.count > 0)   .withmessage("{propertyname} must greater '0'")   .when(p => !p.existingcustomer); 

second, can provide validator competitorproducts class whole. allow have fluentvalidation manage error message , code. work if have other validations must occur on class, might overkill if need validate single property.

  public class prospectvalidator: abstractvalidator<prospect>     {         public currentuservalidator()         {             rulefor(p => p.competitorproducts)               .cascade(cascademode.stoponfirstfailure)               .notnull()               .setvalidator(new competitorproductsvalidator())               .when(p => !p.existingcustomer);         }     }      public class competitorproductsvalidator : abstractvalidator<prospect.competitorproducts>     {         public competitorproductsvalidator()         {             rulefor(p => p.count)               .greaterthan(0);         }     } 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -