A little introduction of Microsoft Enterprise Library Validation block - Validation block tutorial 2/4

 

Microsoft Enterprise Library provide a lot of useful common library to build an enterprise application. One of it’s section is about validating the input from users. The Validation Application Block, that’s what they call it provide a set of library of classes to validate .NET framework data types. The validation allow you to validate an application in the following technologies :

1. ASP.NET
2. Windows Form
3. Windows Communications Framework (WCF)

To run the Validation Application Block you need the following :

  • Microsoft Windows XP Professional, Windows Server 2003, or Windows Vista operating system
  • Microsoft .NET Framework 2.0 or 3.0. The Windows Communications Foundation (WCF) adapter requires 3.0.
  • Microsoft Visual Studio 2005 or 2008 development system

There are three ways to perform validation using the Validation Application Block.
1. Using configuration
2. Using attributes
3. Using code

The following validation example taken from the Enterprise Library Documentation that available after you install the Microsoft Enterprise Library.

//Validation Example 1
  1. using Microsoft.Practices.EnterpriseLibrary.Validation;
  2. using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
  3. public class Customer
  4. {
  5. [StringLengthValidator(0, 20)]
  6. public string CustomerName;
  7.  
  8. public Customer(string customerName)
  9. {
  10. this.CustomerName = customerName;
  11. }
  12. }
  13.  
  14. public class MyExample
  15. {
  16. public static void Main()
  17. {
  18. Customer myCustomer = new Customer("A name that is too long");
  19. ValidationResults r = Validation.Validate(myCustomer);
  20. if (!r.IsValid)
  21. {
  22. throw new InvalidOperationException("Validation error found.");
  23. }
  24. }
  25. }

There is a few validator types used in the application to validate the users input. Those validators are :

  • And composite validator
  • Contains characters validator
  • Date time range validator
  • Domain validator<T>
  • Enum conversion validator
  • Not null validator
  • Object collection validator
  • Object validator
  • Or composite validator
  • Property comparison validator
  • Range validator<T>
  • Regular expression validator
  • Relative date time validator
  • String length validator
  • Type conversion validator

Bellow is the simple explanation of the above validator types.
Validator type examples

1. And composite validator
This validator creates a composite validator. Validation requires that all the validators that make up the composite validator be true. For example, you can use the And Composite Validator to require that the Not Null Validator AND the Date Time Range Validator be true. Because the Validation Application Block’s default behavior is to AND validators, you only need this validator to implement complex logic.

The following code example shows the construction of an AndCompositeValidator instance using attributes. The validator combines a NotNullValidator and a StringLengthValidator. Note that this is the default behavior when more than one validator attribute is used. As a result, the ValidatorComposition attribute could be omitted

//And composite validator example
  1. public class Product
  2. {
  3. [ValidatorComposition(CompositionType.And)]
  4. [NotNullValidator]
  5. [StringLengthValidator(10)]
  6. string _productCode;
  7. //use of return with a parameter
  8. public string GetProductCode( )
  9. {
  10. return _productCode;
  11. }
  12. // …
  13. }

2. Contains characters validator
This validator checks that an arbitrary string, such as a string entered by a user in a Web form, contains any or all of the characters that are specified in the parameters.

The following code example uses attributes to ensure that the product code contains the character “f”, the character “s” and the character “p”.

//Contains characters validator example
  1. public class Product
  2. {
  3. [ContainsCharactersValidator("fsp", ContainsCharacters.All)]
  4. public string ProductCode
  5. {
  6. get
  7. {
  8. return _productCode;
  9. }
  10. }
  11. // …
  12. }

3. Date time range validator
This validator checks that a DateTime object falls within the specified range.

The following code example checks that the expiration date is before January 20, 2010.

//Date time range validator example
  1. public class Product
  2. {
  3. [DateTimeRangeValidator("2010-01-20T00:00:00")]
  4. public DateTime ExpirationDate
  5. {
  6. get
  7. {
  8. return expirationDate;
  9. }
  10. }
  11. // …
  12. }

4. Domain validator
This validator checks that a value is one of the specified values in a specified set. For example, it can check that a name is “Tom”, “Dick”, “Harry”, “George” or that an integer is 2, 3, 5, 7, or 11. If the set only contains one value, you can use this validator to check for equality.

The following code example checks that the sales unit is “each”, “dozen”, or “gross”.

//Domain validator example
  1. public class Product
  2. {
  3. [DomainValidator("each", "dozen", "gross")]
  4. public string SalesUnit
  5. {
  6. get
  7. {
  8. return salesUnit;
  9. }
  10. }
  11. // …
  12. }

5. Enum conversion validator
This validator checks that a string can be converted to a value in a specified enum type. For example, it can check that “Blue” can be converted to a value in the Color enumerator.

The following code example checks that the sales unit is a string that can be converted to a value of the Unit enumeration. For example, the string “Each” is allowed.

//Enum conversion validator
  1. public class Product
  2. {
  3. enum Unit   {
  4. Each, Dozen, Gross
  5. }
  6. [EnumConversionValidator(typeof(Unit))]
  7. public string SalesUnit
  8. {
  9. get
  10. {
  11. return salesUnit;
  12. }
  13. }
  14. // …
  15. }

6. Not null validator
This validator checks that the value is non-null.

The following code example checks whether the Manufacturer property contains the null value.

//Not null validator
  1. public class Product
  2. {
  3. [NotNullValidator]
  4. public Company Manufacturer
  5. {
  6. get
  7. {
  8. return manufacturer;
  9. }
  10. }
  11. // …
  12. }

7. Object collection validator
This validator checks that the object is a collection of the given type and then invokes validation on each element of the collection. If the object you want to validate is null, the validation is ignored. If the object you want to validate is not a collection, then the validation fails and the rule set is not applied. If there are elements in the collection that are of a different type then the one you specified for the object, then the validation for these elements fails but this does not affect validation for the other elements.

The following code example checks that each part in a kit’s part list meets the requirements of the Part type’s validator. The Part type’s validator checks that the name is fewer than 20 characters and that the manufacturer’s URL is well formed according to a particular regular expression pattern.

//Object collection validator
  1. public class Part
  2. {
  3. [StringLengthValidator(20)]
  4. string name;
  5. [RegexValidator("http://(www\.)?([^\.]+)\.com")]
  6. string manufacturerUrl;
  7. // …
  8. }
  9. public class Kit
  10. {
  11. [ObjectCollectionValidator(typeof(Part)]
  12. public Part[] PartList
  13. {
  14. get
  15. {
  16. return partList;
  17. }
  18. }
  19. // …
  20. }

8. Object validator
This validator causes validation to occur on an object reference. All validators defined for the object’s type will be invoked, just as if the Validation.Validate method had been called on the object. If the object you want to validate is null, the validation is ignored. If the reference is to an instance of a type that is not compatible with the configured target’s type then the validation fails. This validator is helpful for validating tree-structured data.

The following code example checks that the Part object that is returned by the OrderedPart property meets the requirements of the Part class’ validator. The Part class’ validator checks that the name is fewer than 20 characters and that the manufacturer URL is well formed according to a particular regular expression pattern.

//Object validator
  1. public class Part
  2. {
  3. [StringLengthValidator(20)]
  4. string name;
  5. [RegexValidator("http://(www\.)?([^\.]+)\.com")]
  6. string manufacturerUrl;
  7. // …
  8. }
  9. public class OrderLineItem
  10. {
  11. [NotNullValidator]
  12. [ObjectValidator]
  13. public Part OrderedPart
  14. {
  15. get
  16. {
  17. return partList;
  18. }
  19. }
  20. // …
  21. }

9. Or composite validator
This validator creates a composite validator. Validation requires that at least one of the validators that make up the composite validator be true. For example, you can use the Or Composite Validator to require that the Not Null Validator OR the Date Time Range Validator be true.

This example shows the construction of an OrCompositeValidator object using attributes. The validator combines a NotNullValidator and a StringLengthValidator.

//Or composite validator
  1. public class Product
  2. {
  3. [ValidatorComposition(CompositionType.Or)]
  4. [NotNullValidator]
  5. [StringLengthValidator(10)]
  6. public string ProductCode
  7. {
  8. get
  9. {
  10. return _productCode;
  11. }
  12. }
  13. // …
  14. }

10. Property comparison validator
This validator compares the value to be checked with the value of a property.

The following code example checks that, for an AuctionItem object, the current bid is greater than or equal to the minimum bid.

//Property comparison validator
  1. public class AuctionItem
  2. {
  3. public double MinimimumBid
  4. {
  5. get
  6. {
  7. return minimumBid;
  8. }
  9. }
  10. [PropertyComparisonValidator("MinimumBid",
  11. ComparisonOperator.GreaterThanEqual)]
  12. public double CurrentBid
  13. {
  14. get
  15. {
  16. return currentBid;
  17. }
  18. }
  19.  
  20. // …
  21. }

11. Range validator
This validator checks that a value falls in a specified range. The range may be either closed, which means it has both a lower and an upper bound specified, or open, which means that it only has one boundspecified.
The Range Validator can be used with any type that implements the IComparable interface. This includes all numeric types and strings. While it is possible, in code, to use this validator with DateTime types, the Date Time Range Validator may be a better choice because it allows you to take advantage of attributes and configuration.

The following code example checks that the Age property is between 0 and 110, inclusive.

//Range validator
  1. public class Person
  2. {
  3. [RangeValidator(0, RangeBoundaryType.Inclusive,
  4. 110, RangeBoundaryType.Inclusive)]
  5. int Age
  6. {
  7. get
  8. {
  9. return this.CalculateAge();
  10. }
  11. )
  12. // …
  13. }

12. Regular expression validator
This validator checks that the value matches the pattern given by a regular expression.

The following code example checks that the e-mail address is formed according to the pattern given by the regular expression.

//Regular expression validator
  1. public class Person
  2. {
  3. [RegexValidator(@”\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]
  4. public string EmailAddress
  5. {
  6. get
  7. {
  8. return emailAddress;
  9. }
  10. }
  11. // …
  12. }

13. Relative date time validator
This validator checks that the DateTime value falls within a specified range using relative times and dates.

The following code example attaches the RelativeDateTimeValidator attribute to the DateOfBirth property and checks to see if the user is 18 years or older.

//Relative date time validator
  1. public class Person
  2. {
  3. [RelativeDateTimeValidator(-120, DateTimeUnit.Year, -18, DateTimeUnit.Year,
  4. Ruleset="RuleSetA", MessageTemplate="Must be 18 years or older.")]
  5. public DateTime DateOfBirth
  6. {
  7. get
  8. {
  9. return dateOfBirth;
  10. }
  11. }
  12. }

14. String length validator
This validator checks that the length of the string is within the specified interval. The interval may include or exclude the endpoints. The lower or upper bound of the interval can be omitted.

The following code example checks that the product code is a string between 1 and 10 characters long.

//String length validator
  1. public class Product
  2. {
  3. [StringLengthValidator(1, 10)]
  4. public string ProductCode
  5. {
  6. get
  7. {
  8. return productCode;
  9. }
  10. }
  11. // …
  12. }

15. Type conversion validator
This validator checks that a string can be converted to a specific type. For example, the validator can check that “6.32″ can be converted to a Double type, or that “2007-02-09″ can be converted to a DateTime type.

The following code example checks to see if the string DiscountString can be converted to type Double.

//Type conversion validator
  1. public class Product
  2. {
  3. [TypeConversionValidator(typeof(double))]
  4. public string DiscountString
  5. {
  6. get
  7. {
  8. return discountString;
  9. }
  10. }
  11. // …
  12. }

That is a simple example about what are you going to do in the next section of this tutorial. Now proceed to the next page.

<< back next >>

Related Articles

Leave a Reply