For the next example, the DomainValidator base class
validates items that exist in a list, passed to it through the object's
constructor. The list has to be defined statically so that it can be available
at the time of construction of the object. This list is available at the time
of validation, so if the item does not exist in the list, then the validation
fails. This occurs in the DoValidate method for us, and no coding effort is
needed.
First, we work with a static array of zip codes, which will
be used to validate the data. Assume that in the form we only have a limited
list of zip codes that are allowed; so only users in that zip code can work
with the form. If they enter in a value outside of the zip code array, an error
is generated. Although the form could use a drop down box, for the sake of the
example, we are using a textbox, which means the zip code property is a
free-form text property and we need proper validation setup. We begin with the
list of values.
Listing 4
private static List<string> ZIPS =
new List<string>(new string[] { "15601", "15602",
"15603", "15604", "15605", "15607", "15607", "15608",
"15609" });
This list gets passed through the constructor as shown
below. Because the list is static, it is available at construction.
Listing 5
public ValidZipCodeValidator() : base(ZIPS) { }
DoValidate does not need to be overridden because it
validates the list properly, but it could be if desired. The new zip code
property definition appears below. The validator attribute takes no
constructors, so no additional properties, except for the optional ones, need
to be provided.
Listing 6
[RegexValidator(@"\d{5}", "The zip code entered is not five digits", Ruleset =
"primary"), ValidZipCodeValidator(Ruleset = "primary")]
public string ZipCode
{
get
{
return _zipCode;
}
set
{
_zipCode = value;
}
}