FluentValidation NotEmpty and EmailAddress example

24.7k views Asked by At

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

There are 1 answers

0
Yannick Meeus On BEST ANSWER

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