Validating with Lambda Expressions
June 28, 2008 – 15:29
I’ve recently been working on a small library for doing validation with lambda expressions. It allows you to run a set of validators against an object, then collects the validation errors in a list. Here are some examples:
var person = new Person(); var validator = Validator.For(person).Rules( rule => rule.For(p => p.Forename).NotNull(), //Forename cannot be null rule => rule.For(p => p.Id).NotEqual(0) //The Id must not be equal to 0 ); //run the validators bool success = validator.Validate(); //Collect the errors IList<string> errors = validator.Errors;
It is also possible to chain validators together:
//Forename cannot be null, cannot be equal to 'Foo' and must be between 1-10 characters. Validator.For(person).Rules( rule => rule.For(p => p.Forename).NotNull().NotEqual("Foo").Length(1, 10) );
If a validator fails, then it will put an error message into the errors collection. For example, the above NotEqual validator would produce an error like ‘Forename’ should not be equal to ‘Foo’. You can change the name of the field by calling the WithName method:
Validator.For(person).Rules( rule => rule.For(p => p.Forename).NotEqual("Foo").WithName("First Name") );
The error would now be generated as ‘First Name’ should not be equal to ‘Foo’
You can also replace the entire error message by using WithMessage
Validator.For(person).Rules( rule.For(p => p.Forename).NotEqual("Foo").WithMessage("Please ensure that you have entered a sensible first name.") );
The source code is available in my svn repository.
One Response
Very cool, thanks!