public class CustomerValidator : AbstractValidator<CustomerModel> { public CustomerValidator() { RuleFor(x => x.Name).NotNull().NotEmpty(); RuleFor(x => x.Name).Length(20, 250); RuleFor(x => x.PhoneNumber).NotEmpty().WithMessage("Please specify a phone number."); RuleFor(x => x.Age).InclusiveBetween(18, 60); // Complex Properties RuleFor(x => x.Address).InjectValidator(); // Other way //RuleFor(x => x.Address).SetValidator(new AddressValidator()); // Collections of Complex Types //RuleForEach(x => x.Addresses).SetValidator(new AddressValidator()); } } // Address Validator public class AddressValidator : AbstractValidator<AddressModel> { public AddressValidator() { RuleFor(x => x.State).NotNull().NotEmpty(); RuleFor(x => x.Country).NotEmpty().WithMessage("Please specify a Country."); RuleFor(x => x.Postcode).NotNull(); RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode"); } private bool BeAValidPostcode(string postcode) { // custom postcode validating logic goes here. return true; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter