Install the FluentValidation .NET library for validation.
Below is our sample Contact class and its corresponding validator class.
The validator class needs to inherit AbstractValidator<Contact> and define the validation rules in the constructor using the RuleFor method.
Instantiate the validator class, and pass the object to be validated.
Here we have passed incorrect values for all the properties of the contact.
The ValidationResult holds all the validation error details.
Give it a try – https://docs.fluentvalidation.net/en/latest/index.html
Hope it helps..
using FluentValidation;
using FluentValidation.Results;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FluentValidator
{
class Program
{
static void Main(string[] args)
{
var myContact = new Contact();
var contactValidator = new ContactValidator();
myContact.FirstName = "";
myContact.LastName = "Lei";
myContact.Email = "aa.gcom";
myContact.Age = 10;
myContact.FamilyStatusCode = (FamilyStatusCode)Enum.Parse(typeof(FamilyStatusCode),"5");
ValidationResult result = contactValidator.Validate(myContact);
}
}
class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int Age { get; set; }
public FamilyStatusCode FamilyStatusCode { get; set; }
}
enum FamilyStatusCode
{
Single = 1,
Married = 2,
Divorced = 3,
Widowed = 4
}
class ContactValidator : AbstractValidator<Contact>
{
public ContactValidator()
{
// First Name should not be null
RuleFor(contact => contact.FirstName).NotEmpty();
// Last Name should not be null and minimum length should be 4
RuleFor(contact => contact.LastName).NotNull().MinimumLength(4);
// Email Address Validation
RuleFor(contact => contact.Email).EmailAddress();
// Age should be between 18 to 60
RuleFor(contact => contact.Age).ExclusiveBetween(18, 60);
// Family Status Code Enum should be a valid value
RuleFor(contact => contact.FamilyStatusCode).IsInEnum();
}
}
}