ASP.NET Web Pages - Creating Custom Validators

4.12 (24 votes)

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){
                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){
            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 (!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">
        <meta charset="utf-8" />
        <title>Validator Test</title>
        <form method="post">
            <div>@Html.TextBox("Email") <span>@Html.ValidationMessage("Email")</span></div>
            <div><input type="submit" /></div>

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.


You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 22597


- _pietro

anyone tried to use Email as extended method of Validator?!? it seems you can do that...thanks

- _pietro

can't do that...sorry

- Gianmaria Gregori

Really interesting.
However, why don't you add a default errorMessage EmailValidator?
Something like:
public EmailValidator(string errorMessage = "Must be a valid email pattern") : base(errorMessage){}

- Mike


You can add your default message to the EmailValidator class if you like, but I decided to add it to the Email method of the MyValidator class instead. This is how the built-in validators work. If the error message is empty, a default error message is retrieved from resource files. That is then passed to the constructor of the specific IValidator. You can see the source code for the Validator class here.

- neetusahani


- _James

How would I get this to work in a Web Form?

- Mike


The validators featured above are for the Web Pages framework, not the Web Forms framework. Web Forms have their own validators - one of which is called the CustomValidator

- mnguyen

Does your custom validation class support client-side validation?

- Mike


No it doesn't. I may well look at that in a future article.

- Tunde Szabo

If you have two radio buttons and an input type text how can you validate that the input type text is not empty if the second radion button is selected.

- Mike


You would do that with simple conditional logic in a code block. It's not a job for a validator.

Recent Comments

Pam 30/08/2017 11:30
In response to Sending Email in Razor Pages
Mike, RazorPages sound like a nice choice for somebody still working in ASP classic who wants to to...

Robby Robson 15/08/2017 00:43
In response to Routing in Razor Pages
Mike: great stuff. Now that .Core Standard 2.0 is formally out, how soon will you rewrite your book...

Satyabrata Mohapatra 28/07/2017 08:59
In response to Sending Email in Razor Pages
Bit off topic, but congratulation sir for your MVP award. You deserve it !!!...

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...