CustomerValidator : AbstractValidator<CustomerModel>

PHOTO EMBED

Fri Apr 22 2022 19:22:51 GMT+0000 (Coordinated Universal Time)

Saved by @iamsingularity #csharp

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;
    }
}
content_copyCOPY