You can also use Fluent Validation to do this. https://docs.fluentvalidation.net/en/latest/aspnet.html
Your Model Class:
public class Customer
{
public int Id { get; set; }
public string Surname { get; set; }
public string Forename { get; set; }
public decimal Discount { get; set; }
public string Address { get; set; }
}
You would define a set of validation rules for this class by inheriting from AbstractValidator<Customer>
:
using FluentValidation;
public class CustomerValidator : AbstractValidator<Customer>
{
RuleFor(customer => customer.Surname).NotNull();
. . . etc;
}
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);
The Validate method returns a ValidationResult
object. This contains two properties:
IsValid
- a boolean that says whether the validation succeeded.
Errors
- a collection of ValidationFailure objects containing details about any validation failures.
The following code would write any validation failures to the console from your controller or even from your service or repository:
using FluentValidation.Results;
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
if(! results.IsValid)
{
foreach(var failure in results.Errors)
{
Console.WriteLine("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
}
}
You can also inject the validator inside Program.cs
, read here : https://docs.fluentvalidation.net/en/latest/di.html