The first of two examples will be a zip code validator
because zip code validation is easier. Zip codes use a pattern that does not
vary much, like phone numbers do. Some countries have varying area codes
lengths, which affect the number of digits in the rest of the number. Zip
Codes usually do not have that complexity. I added some additional
information, determining whether a zip code could or could not be null, through
the following property.
Listing 1
public class ZipCodeValidator: Validator < string >
{
private bool _allowNulls = false;
public bool AllowNulls
{
get
{
return _allowNulls;
}
set
{
_allowNulls = value;
}
}
}
The template and validation regular expression are defined
in properties, which can be overridden in the derived implementation if desired.
The implementation is below.
Listing 2
protected override string DefaultMessageTemplate
{
get
{
return ValidationResources.Zip_DefaultMessage;
}
}
protected virtual string ZipCodeRegex
{
get
{
return ValidationResources.ZipCodeRegex;
}
}
I have included information for three cultures shown in this
example, which I will expand upon in the future.
Culture
|
Validation Expression
|
Default Message Template
|
France
|
\d{5}
|
{1} de '{0} 'n'est pas un code postal valide.
|
Italy
|
(IT?-)?\d{5}
|
{1} di '{0} 'non è un codice di postale valido.
|
Default
|
\d{5}
|
The {1} of '{0}' is not a valid zip code.
|
The validation of the zip code is actually really simple; an
error is added to the validation result collection if the zip code provided is
null, empty, or does not meet the validation expression, using the
Regex.IsMatch method. The validation method appears as:
Listing 3
protected override void DoValidate(string objectToValidate, object
currentTarget, string key, ValidationResults validationResults)
{
if (string.IsNullOrEmpty(objectToValidate))
{
if (!this.AllowNulls)
base.LogValidationResult(validationResults, this.GetMessage
(objectToValidate, key), currentTarget, key);
return ;
}
if (!Regex.IsMatch(objectToValidate, this.ZipCodeRegex))
base.LogValidationResult(validationResults, this.GetMessage
(objectToValidate, key), currentTarget, key);
}
The Regex processing is really simple with the IsMatch
static method. The validation expression for US zip codes (and other five
digit countries) is this: ^\d{5}$. It is important to have the ^ character at
the beginning and the $ at the end because it denotes that the expression
processes the whole string, not a portion of it. If you are unfamiliar with
regular expressions, there are many resources available on the internet.