Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 943
Kris-I Avatar asked Apr 12 '16 09:04

Kris-I


1 Answers

Use where or unless.

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

EDIT: Updated documentation link.

like image 191
Nino Avatar answered Sep 20 '22 04:09

Nino