Using Validation Block Attributes
Validation attributes (both the built-in Validation Application Block attributes and those described in the topic Using Data Annotation Attributes) can be used with various targets that include classes, fields, properties, methods, and (in limited cases) parameters. For information, see Validation Attribute Targets. There is also a set of attributes that allow you to change the behavior of other attributes. These are discussed in Validation Modifier Attributes. You can also specify the attributes you want to use in a separate metadata class. For more details of this, see Defining Attributes in Metadata Classes.
Using Validation Block Attributes to Define Validation Rule Sets
You can include Validation Application Block attributes in your code to define rule sets (you cannot specify named rule sets when you use .NET Data Annotation attributes). This is an alternative to using configuration or code. If you do not specify a name for an attribute validation rule, it is part of the default rule set. The following code example shows how to use attributes to define a rule set named "RuleSetA."
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
public class Customer
{
private string firstName;
private string lastName;
private DateTime dateOfBirth;
private string email;
private Address address;
private int rewardPoints;
[StringLengthValidator(1, 50, Ruleset="RuleSetA",
MessageTemplate="First Name must be between 1 and 50 characters")]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[StringLengthValidator(1, 50, Ruleset = "RuleSetA",
MessageTemplate = "Last Name must be between 1 and 50 characters")]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
[RelativeDateTimeValidator(-120, DateTimeUnit.Year, -18,
DateTimeUnit.Year, Ruleset="RuleSetA",
MessageTemplate="Must be 18 years or older.")]
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
[RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
Ruleset = "RuleSetA")]
public string Email
{
get { return email; }
set { email = value; }
}
[ObjectValidator("ValidAddress", Ruleset="RuleSetA")]
public Address Address
{
get { return address; }
set { address = value; }
}
[RangeValidator(0, RangeBoundaryType.Inclusive, 1000000,
RangeBoundaryType.Inclusive, Ruleset="RuleSetA",
MessageTemplate="Rewards points cannot exceed 1,000,000")]
public int RewardPoints
{
get { return rewardPoints; }
set { rewardPoints = value; }
}
}
'Usage
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports Microsoft.Practices.EnterpriseLibrary.Validation
Imports Microsoft.Practices.EnterpriseLibrary.Validation.Validators
Public Class Customer
Private _firstName As String
Private _lastName As String
Private _dateOfBirth As DateTime
Private _email As String
Private _address As Address
Private _rewardPoints As Integer
<StringLengthValidator(1, 50, Ruleset:="RuleSetA", _
MessageTemplate:="First Name must be between 1 and 50 characters")> _
Public Property FirstName() As String
Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value
End Set
End Property
<StringLengthValidator(1, 50, Ruleset:="RuleSetA", _
MessageTemplate:="Last Name must be between 1 and 50 characters")> _
Public Property LastName() As String
Get
Return _lastName
End Get
Set(ByVal value As String)
_lastName = value
End Set
End Property
<RelativeDateTimeValidator(-120, DateTimeUnit.Year, -18, _
DateTimeUnit.Year, Ruleset:="RuleSetA", _
MessageTemplate:="Must be 18 years or older.")> _
Public Property DateOfBirth() As DateTime
Get
Return _dateOfBirth
End Get
Set(ByVal value As DateTime)
_dateOfBirth = value
End Set
End Property
<RegexValidator("\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", _
MessageTemplate:="Invalid e-mail address", _
Ruleset:="RuleSetA")> _
Public Property Email() As String
Get
Return _email
End Get
Set(ByVal value As String)
_email = value
End Set
End Property
<ObjectValidator("ValidAddress", Ruleset:="RuleSetA")> _
Public Property Address() As Address
Get
Return _address
End Get
Set(ByVal value As Address)
_address = value
End Set
End Property
<RangeValidator(0, RangeBoundaryType.Inclusive, 1000000, _
RangeBoundaryType.Inclusive, Ruleset:="RuleSetA", _
MessageTemplate:="Rewards points cannot exceed 1,000,000")> _
Public Property RewardPoints() As Integer
Get
Return _rewardPoints
End Get
Set(ByVal value As Integer)
_rewardPoints = value
End Set
End Property
End Class
This code defines a class named Customer that includes a number of properties such as FirstName and LastName. Attributes that are attached to these properties associate them with validators. For example, the StringLengthValidator attribute is attached to the FirstName property and associates it with the StringLengthValidator class. This attribute includes two constructor parameters that constrain the length of the value contained in the FirstName field, a parameter that specifies the rule set to apply, and a parameter that defines the message template. The message template contains the message that is returned if validation fails.
The Ruleset parameter of the validation attributes indicates that the application block will use "RuleSetA" instead of the anonymous, default rule set. In this example, the ObjectValidator attribute is a part of the "RuleSetA" rule set and refers to the "RuleSetA" rule set of the Address class.
Validation Attribute Targets
Validation attributes can be used with various targets. The following table lists the targets and describes how the validators associated with the attributes behave.
Target |
Behavior of associated validator |
---|---|
Class |
The validator checks the object. Typically, these attributes are custom type-level validators supplied by the user. The supplied validators, with the exception of the Not Null validator, object collection validator, and composite validators, can only be used at the member level and not the class level. |
Field |
The validator checks the value of the field. |
Property |
The validator checks the value of the get property. |
Method |
The validator checks the return value of the method. A validator attribute can only be applied to methods that take no arguments. |
Parameter |
The Validation Application Block ignores attributes attached to parameters except for WCF and the Policy Injection Application Block Validation Call Handler. |
Validation Modifier Attributes
Validation modifier attributes allow you to change the way validation attributes behave. The validation modifier attributes are the following:
- ValidatorComposition
- IgnoreNulls
- HasSelfValidation
- SelfValidation
The ValidatorComposition attribute allows you to provide a composite validator as an attribute. With it, you can override the default behavior that occurs when you use more than one validator attribute. You can specify either CompositionType.And or CompositionType.Or as an argument to this attribute. The default composition type is AND. The default behavior is the same as if you do not use the attribute. Typically, you use the AND composition type when the logic is complex and requires OR operations as well as AND operations.
You can have a composite validator within the context of Enterprise Library Configuration, Enterprise Library Validation Application Block, and DatAnnotations. When using DataAnnotations attributes, the composite validator can only be an implicit AND of the attributes. For Validation Application Block attributes, the composite validator is formed by using an AND of the attributes by default. The composite validator logic can be changed through the ValidatorComposition attribute.
Enterprise Library Configuration does not rely on attributes. Configuration has its own structure for composing validators. The validator that will actually be used incorporates the rules from these three sources by using a logical AND of the rules. The result is independent of how the validators from each source are composed.
The IgnoreNulls attribute specifies that the other validators will not be called if the value that you are checking is null.
The following table shows some examples of how you can combine attributes to achieve the equivalent of the common ways you might use of the And and Or validators in a configuration rule set.
Attributes |
Equivalent in Configuration |
---|---|
[ValidatorX] [ValidatorY] [ValidatorZ] |
And Composite Validator
|
[ValidatorComposition(CompositionType.Or)] [ValidatorX] [ValidatorY] [ValidatorZ] |
Or Composite Validator
|
[IgnoreNulls] [ValidatorX] [ValidatorY] |
Or Composite Validator
|
The HasSelfValidation attribute marks a class that contains Self validation logic. The SelfValidation attribute marks Self validation methods within that class. For more information, see Using Self Validation.