The following is a user business component that contains the
typical user information. This class has the added validation configured as
attributes within the class.
Listing 1
public class User
{
private string _email = string.Empty;
private string _name = string.Empty;
private string _phone = string.Empty;
[StringLengthValidator(7, RangeBoundaryType.Inclusive, 150,
RangeBoundaryType.Inclusive,
"Email address must be from 7 and 150 characters", Ruleset = "primary"),
ContainsCharactersValidator("@.", ContainsCharacters.All,
"Email must have at an @ and at least one decimal", Ruleset = "primary")]
public string Email
{
get
{
return _email;
}
set
{
_email = value;
}
}
[StringLengthValidator(3, RangeBoundaryType.Inclusive, 150,
RangeBoundaryType.Inclusive,
"Name must be between 3 and 150 characters long", Ruleset = "primary"),
ContainsCharactersValidator(" ", ContainsCharacters.All,
"Name must have at least a space between the names", Ruleset = "primary")]
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
[StringLengthValidator(7, RangeBoundaryType.Inclusive, 10,
RangeBoundaryType.Inclusive,
"Phone number must be between 7 and 10 characters", Ruleset = "primary"),
RegexValidator(@"(\d{3})?\d{7}",
"Phone number is not valid; it can be numbers only", Ruleset = "primary")]
public string Phone
{
get
{
return _phone;
}
set
{
_phone = value;
}
}
}
As you can see, several of the validator attributes are
defined on the properties of the class. These exist in the
Microsoft.Practices.EnterpriseLibrary.Validation.Validators namespace and are
used to validate the data entered. Of the validators above, here are the
ones used and an explanation of what they do:
• StringLengthValidator - This validator ensures the strings
are within the defined length.
• ContainsCharactersValidator - This validator ensures that the data for the
property has the characters defined in the string. It could be one
of or all of the characters, as defined by the ContainsCharacters enumeration.
• RegexValidator - This validator uses a regex expression to perform the
validation.
Each validator attribute has several constructor overloads, allowing you to
specify a combination of configuration options for each validator. Notice
that each one has a place where you can enter a message template, allowing you
to specify a detailed error message for the problem. This is used to
specify the detailed error messages in the ASP.NET validation scheme as we will
see soon. Note also that a Ruleset property is defined. The
validation works with varying rulesets so that you can change between the
rulesets if so desired. It is an optional property, but can be set using
the "Ruleset=" notation in C# or "Ruleset:=" notation in VB.NET.