Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation NotEmpty and EmailAddress example

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.");
like image 813
Ravi Ram Avatar asked Jun 08 '15 18:06

Ravi Ram


People also ask

How does FluentValidation work?

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.

What is FluentValidation C#?

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.

Should I use fluent validation?

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.


Video Answer


1 Answers

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");
like image 145
Yannick Meeus Avatar answered Oct 13 '22 04:10

Yannick Meeus