ASP.NET Web Pages - Creating Custom Validators

Version 2 of the Web Pages framework includes a new validation framework. Included are a number of specific validators that cover common scenarios such as validating for presence, data type or range. It may be however, that you want to create your own custom validator to test for something that isn't covered by the existing validators, or to combine multiple tests in one composite validator. Fortunately, the Web Pages team have made the validation system extensible so that you can create your own validators.

Validators should inherit from RequestFieldValidatorBase, which is an abstract class in System.Web.WebPages specifically designed to act as a base class for validation helpers. RequestFieldValidatorBase includes an abstract method - IsValid(), which must be implemented in any class that derives from the base class. To see how this works, here's a class that is used to validate a string to ensure that it meets the pattern of a valid email address:

using System;
using System.Web; 
using System.Web.WebPages;
using System.Net.Mail;

public class EmailValidator : RequestFieldValidatorBase
{
    public EmailValidator(string errorMessage = null) : base(errorMessage){}

    protected override bool IsValid(HttpContextBase httpContext, string value){
        try{
                MailAddress email = new MailAddress(value);
                return true;
            }
            catch(FormatException fex){
                return false;
            }
    }
}

To test this out for yourself, save this as EmailValidator.cs in your App_Code folder.

RequestFieldValidatorBase requires derived classes to include a constructor that takes a string representing the error message to be displayed in the event that the form field value doesn't pass the validation test. The test itself is coded in the IsValid() method, which returns a bool representing pass or fail. In the example above, the string is passed to the MailAddress constructor which throws a FormatException if it isn't a valid email address. This is caught and the method returns false. Otherwise it is considered a valid format for an email address and true is returned.

You could register your EmailValidator in your .cshtml page as it is:

Validation.Add("Email", new EmailValidator());

However, there is a problem with this approach. Validators deriving from RequestFieldValidatorBase require error messages, and there is currently no way to protect against a programmer forgetting to supply one, so the way to get round this is to provide a default one yourself. You can do this by creating a method that returns an IValidator for plugging into the ValidationHelper's Add method. Here's an example:

using System.Web.WebPages;

public class MyValidator
{
    public static IValidator Email(string errorMessage = null){
        if(string.IsNullOrEmpty(errorMessage)){
            errorMessage = "Must be a valid email pattern";
        }
        return new EmailValidator(errorMessage);
    }
}

This Email method now tests to see if an error message has already been provided. If not, a default error message is supplied instead, and an instance of EmailValidator is returned with that error message. If you want to try this out for yourself, save the snippet above as MyValidator.cs in App_Code. Then register the validator in your .cshtml page as follows:

Validation.Add("Email", MyValidator.Email());

Here's a complete .cshtml file that includes a form with a text box that expects a valid email address, and uses the custom validator to validate the supplied value:

@{
    Validation.Add("Email", MyValidator.Email());
    var message = "";
    if(IsPost){
        if (!Validation.IsValid()) {
            ModelState.AddFormError("There are some errors with your submission"); 
        }
        else {
           message = "Your valid email address is: " + Request["Email"];
        }
    }
}

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Validator Test</title>
    </head>
    <body>
        <div>@Html.ValidationSummary(true)</div>
        <div>@message</div>
        <form method="post">
            <div>@Html.TextBox("Email") <span>@Html.ValidationMessage("Email")</span></div>
            <div><input type="submit" /></div>
        </form>
    </body>
</html>

If you try this out for yourself, you can test passing your own error message when registering the validator:

Validation.Add("Email", MyValidator.Email("Provide a valid email, please"));

Most of the time, the validators provided by the ASP.NET Web Pages validation framework will be enough for your requirements, but if you find yourself needing something extra, this article should provide you with the foundations for building your own validators.