I am using fluent validation library for my asp.net mvc5 project . my requirement is if user input email then if validate valid email address otherwise its not validate it is valid email address or not
Asked
Active
Viewed 2,760 times
2
-
1Although the answer in the linked question is similar to the answer for this question, they are not the same question. The other question asks "how do I validate NOT null AND valid email", whereas this question asks "how do I validate null OR valid email". – OutstandingBill May 03 '22 at 21:46
1 Answers
1
You can simply do as follows with Fluent Validation
method chaining:
RuleFor(s => s.Email).NotEmpty().WithMessage("Email address is required")
.EmailAddress().WithMessage("Your email address is not valid");
If your email field is not required
then validate as follows:
RuleFor(s => s.Email).EmailAddress().WithMessage("Your email address is not valid");
try this, If your email field is not required then validate Email Address:
RuleFor(e => e.Email).EmailAddress().When(x => !string.IsNullOrEmpty(x.Email)).WithMessage("Your email address is not valid");

Zaid Qassim
- 109
- 1
- 5

TanvirArjel
- 30,049
- 14
- 78
- 114
-
My requirement is if user input email text box then it validate otherwise it not checking any validation for this text box – tapos ghosh Feb 08 '19 at 09:43
-
-
yes please tell me how i validate this scenario RuleFor(x => x.Email).EmailAddress().When(x=>x.Email.IsNotNullOrEmpty()).Must(EmailExits); but this code is not working plz help how can i solve this problem – tapos ghosh Feb 08 '19 at 09:45
-
Have you tried this: `RuleFor(s => s.Email).EmailAddress().WithMessage("Your email address is not valid");` – TanvirArjel Feb 08 '19 at 09:47
-
only validate this text field if user input anything this text box otherwise not – tapos ghosh Feb 08 '19 at 09:48
-
Yes! Understood Try this : `RuleFor(s => s.Email).EmailAddress().WithMessage("Your email address is not valid");` and make sure that `Email` field in your model does not contain any `Required` attribute. – TanvirArjel Feb 08 '19 at 09:48
-
1Your rule for non-required Email didn't work for me. Had to use `RuleFor(e => e.EmailAddress).EmailAddress().When(x => !string.IsNullOrEmpty(x.EmailAddress));` Otherwise it threw a validation error if it was empty. – Laurie Dickinson Apr 10 '20 at 16:52
-
Had the same issue. I can confirm that even if you don't mark the property as required, it still gets validated unless you add what @LaurieDickinson said `.When(x => !string.IsNullOrEmpty(x.EmailAddress));` – FMR Apr 23 '20 at 09:52