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.


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


- _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

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....