Barış Kısır

Software Developer

Navigation
 » Home
 » About
 » Resume
 » Projects
 » Contact
 » RSS

Fluent Validation Usage

10 Dec 2016 » csharp

How do you validate inputs?

Are you still writing tons of if-else condition for validation?

Now its time to go forward!

Fluent Validation

Validation has never been easier!

Installation with NuGet

Install-Package FluentValidation -Version 6.2.1

Lets create class for your object

public class Employee
{
	public string Name { get; set; }
	public int Age { get; set; }
	public string Email { get; set; }
}

Configuring validation

public class EmployeeValidator : AbstractValidator<Employee>
{
	public EmployeeValidator()
	{
		RuleFor(x => x.Age)
		.Must(x => x >= 18 && x <= 100)
		.WithMessage("Age must be between 18 and 100");

		RuleFor(x => x.Name)
		.NotEmpty()
		.WithMessage("Name cannot be empty");
			
		RuleFor(x => x.Email)
		.EmailAddress()
		.WithMessage("This is not a valid email!");
	}
}

Validation handling

Employee employee = new Employee();
employee.Name = txtName.Text;
employee.Age = Int32.Parse(txtAge.Text);
employee.Email = txtEmail.Text;
EmployeeValidator employeeValidator = new EmployeeValidator();
ValidationResult validationResult = employeeValidator.Validate(employee);
if (!validationResult.IsValid)
	{
		lblError.Text = string.Empty;
		foreach (var error in validationResult.Errors)
			{
			lblError.Text += error.ErrorMessage + "<br />";
			}
	}
else
	{
	lblError.Text = "You are ready to go!";
	}

You can download source code from here –> Download

validation-1

validation-2

validation-3

validation-4

validation-5

validation-6