Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FluentValidation.AspNetCore and FluentValidation.MVC6?

How to use FluentValidation.AspNetCore and FluentValidation.MVC6 to validate Entities in AspNetCore , can anyone give me an example ?

like image 957
Mtaraby Avatar asked Oct 17 '16 18:10

Mtaraby


People also ask

What is FluentValidation AspNetCore?

The FluentValidation. AspNetCore package provides auto-validation for ASP.NET Core MVC projects by plugging into ASP. NET's validation pipeline.

How do you validate fluently?

To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate. Customer customer = new Customer(); CustomerValidator validator = new CustomerValidator(); ValidationResult result = validator. Validate(customer);

What is FluentValidation C#?

FluentValidation is a . NET library for building strongly-typed validation rules.


1 Answers

This is working for me:

project.json add:

"FluentValidation.AspNetCore": "6.4.0-beta3"

startup.cs

services
.AddMvc()
.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

Validation:

public class Foo
{
     public string Bar {get; set;}
}

public class FooValidator : AbstractValidator<Foo> 
{
    public FooValidator()
    { 
        RuleFor(x => x.Bar).NotEmpty().WithMessage("Error Message");
    }
}
like image 152
pat Avatar answered Sep 28 '22 03:09

pat