I am using FluentValidation with a login form. The email address field is
Required and Must be a valid email address.
I want to display a custom error message in both cases.
The code I have working is:
RuleFor(customer => customer.email)
.NotEmpty()
.WithMessage("Email address is required.");
RuleFor(customer => customer.email)
.EmailAddress()
.WithMessage("A valid email address is required.");
The above code does work and shows (2) different error messages. Is there a better way of writing the multiple error message for one field?
UPDATE - WORKING
Chaining and add .WithMessage
after each requirement worked.
RuleFor(customer => customer.email)
.NotEmpty()
.WithMessage("Email address is required.")
.EmailAddress()
.WithMessage("A valid email address is required.");
FluentValidation is a server-side library and does not provide any client-side validation directly. However, it can provide metadata which can be applied to the generated HTML elements for use with a client-side framework such as jQuery Validate in the same way that ASP. NET's default validation attributes work.
FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.
Summary. FluentValidation provides a great alternative to Data Annotations in order to validate models. It gives better control of validation rules and makes validation rules easy to read, easy to test, and enable great separation of concerns.
You can just chain them together, it's called Fluent Validation for a reason.
RuleFor(s => s.Email).NotEmpty().WithMessage("Email address is required")
.EmailAddress().WithMessage("A valid email is required");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With