Validating objects using attributes

Let us scratch the surface with a simple Author class, which consists of ID, FirstName, and EmailID properties. We would like to validate based on the given criteria:

  • First name of the author should not be null and should be between 1 and 30 characters.
  • EmailID should not be null or empty and should be a valid E-mail ID.

The Author class marked with the respective Validator attributes is given next:

public class Author
{
public int ID { get; set; }
[NotNullValidator(MessageTemplate = "First Name cannot be null")]
[StringLengthValidator(1, 30, MessageTemplate = "First Name must be between 1 and 30 characters")]
public string FirstName { get; set; }
[RegexValidator(@"w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*", MessageTemplate = "Invalid Email ID")]
public string EmailID { get; set; }
}

The given Author class is marked with the Validator attributes to let the Validation Application Block know that validation has to be done based on the given criteria. So we have specified the criteria; now we have to validate the object in our application. Assume that we receive the First Name and Email ID from the user while registering as a new author. We have to use that input and construct the object and then validate the object to verify whether the input meets the validation criteria. The following code creates a ValidatorFactory and creates a Validator instance by passing the type Author.

AttributeValidatorFactory validatoryFactory = EnterpriseLibraryContainer.Current.GetInstance<AttributeValidatorFactory>();
Validator<Author> validator = validatoryFactory.CreateValidator<Author>();
Author author = new Author();
author.FirstName = null;
author.EmailID = "some invalid email id";
ValidationResults results = validator.Validate(author);
foreach (ValidationResult result in results)
{
Console.WriteLine(result.Message);
}

Tip

Since we are dealing with attribute-based validation we have created an instance of the AttributeValidatorFactory class. Alternatively, ValidatorFactory can also be instantiated to validate rules defined in attributes, configuration, and .NET Data Annotations validation attributes.

The previous code block will result in validation failure and display the following error messages in the console.

  • First Name cannot be null
  • First Name must be between 1 and 30 characters
  • Invalid Email ID
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.53