FluentValidation NotEmpty and EmailAddress example

I am using FluentValidation with an login form. Email Address Field

Required and must have a valid email address.

I want to show a custom error message in both cases.

The code I have 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 really works and shows (2) various error messages. Is there a better way to write multiple error messages for a single field?

UPDATE - WORK

Linking and adding .WithMessage after each requirement is met.

RuleFor(customer => customer.email)
    .NotEmpty()
        .WithMessage("Email address is required.")
    .EmailAddress()
        .WithMessage("A valid email address is required.");
+4
source share
1 answer

You can just bind them together, it's called Fluent Validation for some reason.

RuleFor(s => s.Email).NotEmpty().WithMessage("Email address is required")
                     .EmailAddress().WithMessage("A valid email is required");
+13
source

All Articles