The authorization code validator inherits from another
possible base class, called ValueValidator. This class is also a generic
implementation and provides two message properties to override: one to work
when the property is non-negated and one for negated forms. These properties
are shown below.
Listing 7
protected override string DefaultNegatedMessageTemplate
{
get
{
return @"The authorization code cannot appear with the first letter of
'A'"; }
}
protected override string DefaultNonNegatedMessageTemplate
{
get
{
return "The authorization code must begin with the first letter of 'A'"; }
}
The class also overrides DoValidate, which uses a custom
class to determine whether the validation is successful. This class could
check against an authorization store to ensure an entry exists in the database,
XML file, or some other store. In this example, it just checks to see if the
authorization code starts with the letter "A." If it does, the code
is considered valid. Another validator (StringLengthValidator) is used to
ensure that the authorization code is of the correct length.
Listing 8
protected override void DoValidate(string objectToValidate,
object currentTarget, string key,
ValidationResults validationResults)
{
return AuthorizationCodeRepository.IsValid(objectToValidate);
}
A new property on the User object has been created, called
AuthorizationCode. It has the new property accessors defined as the following.
Listing 9
[
StringLengthValidator(5, RangeBoundaryType.Inclusive,
7, RangeBoundaryType.Inclusive,
"The code is outside the range of valid values",
Ruleset="primary"),
AuthorizationCodeValidator(Ruleset="primary")
]
public string AuthorizationCode
{
get { return _authorizationCode; }
set { _authorizationCode = value; }
}
The authorization code validator attribute takes no
parameters in its constructor, so only the optional parameters need be assigned
here. This could be expanded to include a connection string name or the name of
an XML file to parse; however, this information is more appropriately extracted
from the configuration file or a custom configuration section.