Validate allows you to raise custom ValidationExceptions whenever a validation error occurs. In this section we will look at Validate's support for raising exceptions on validation errors and it's support for raising custom exceptions.

Raising a ValidationException on a validation error:
var person = new Person();
var validator = person.Validate(new ValidationOptions{ThrowValidationExceptionOnError = true}) // The ThrowValidationExceptionOnError property of ValidationOptions controls whether or not an exception should be raised on a validation error. Default is false.
                      .IsNotNull(p => p.FirstName) // This line throws a validation exception. The validation exception contains 1 ValidationError
                      .IsNotNull(p => p.LastName); // This line is not executed
It is possible to wait for all validations to execute before throwing a validation exception.
var validator = person.Validate(new ValidationOptions{ThrowValidationExceptionOnError = true, StopOnFirstError = false})
                      .IsNotNull(p => p.FirstName) // This line does not throw a ValidationException, all validations are now executed
                      .IsNotNull(p => p.LastName)
                      .Throw(); // A Throw is required at the end to raise the ValidationException. A throw raises an exception only if there were validation errors. The ValidationException in this case has 2 ValidationError(s).

Raising a custom validation exception:
It is possible to raise a custom validation exception for validation errors as long as the custom exception inherits from ValidationException. To raise custom exceptions it is also required to create a custom validation result to validation exception transformer. It is however simpler than it sounds as the abstract class ValidationResultToValidationExceptionTransformer has only one abstract method which needs to be implemented.
// Create a custom Validation exception first
public class MyValidationException : ValidationException
{
    .....
}

// Create a ValidationResultToMyCustomValidationTransformer
public class ValidationResultToMyCustomValidationTransformer : ValidationResultToExceptionTransformer
{
    public override Throw()
    {
        // This has access to the validator object after it has run all the validations.
       throw new MyValidationException(Validator.IsValid, Validator.Validations, Validator.Errors);
    }
}

// To raise the custom validation exception on validation errors when validating
var person = new Person();
var validator = person.Validate(new ValidationOptions{ValidationResultToExceptionTransformer = new ValidationResultToMyCustomValidationTransformer()})
                      .IsNotNull(p => p.FirstName); // This now raises a MyValidationException

Go back to documentation

Last edited Jan 5, 2011 at 4:55 PM by ashishsharmaait, version 1

Comments

No comments yet.