18

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.");

1 Answer 1

42

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");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.