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: 22447


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

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...

Mau 06/06/2017 08:58
In response to Razor Pages - The Elevator Pitch
I am missing the razor view code. Thank you for your article. Design pattern should improve the of...

Obinna Okafor 26/05/2017 16:16
In response to Razor Pages - The Elevator Pitch
Thank you for this wonderful piece, Mike. I need more of these...Keep them coming - anything more...

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...