Search code examples
c#.netangularjsfluentvalidation

Check email validity with FluentValidation when property is not empty


I'd like with FluentValidation check the email format. The email is not mandatory. Then I have to check only when the property is not empty.How can I do this ? Below I check all the time.

RuleFor(x => x.Email)
    .EmailAddress()
    .WithLocalizedMessage(() => "My message.");

Thanks


Solution

  • Use where or unless.

    RuleFor(x => x.Email)
        .EmailAddress()
        .WithLocalizedMessage(() => "My message.")
        .Unless(x => string.IsNullOrEmpty(x.Email));
    

    EDIT: Updated documentation link.