ASP.NET Web Pages - Creating Custom 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.Web; using System.Web.WebPages; using System.Text.RegularExpressions; public class EmailValidator : RequestFieldValidatorBase { public EmailValidator(string errorMessage = null) : base(errorMessage){} protected override bool IsValid(HttpContextBase httpContext, string value){ return Regex.IsMatch(value, @"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$"); } }
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 test comprises a Regular Expression match. If the value matches the Regex pattern, it is considered a valid format for an email address and true is returned.
You could simply 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.
Currently rated 4.05 by 22 people
Rate Now!
Date Posted:
31 August 2012 14:33
Last Updated:
Posted by:
Mikesdotnetting
Total Views to date:
10057



Comments
05 September 2012 02:29 from _pietro
anyone tried to use Email as extended method of Validator?!? it seems you can do that...thanks
05 September 2012 23:30 from _pietro
can't do that...sorry
15 September 2012 13:33 from 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){}
15 September 2012 15:59 from Mikesdotnetting
@Gianmaria
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.
17 September 2012 10:03 from neetusahani
nice
08 October 2012 15:55 from _James
How would I get this to work in a Web Form?
08 October 2012 16:51 from Mikesdotnetting
@_James
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
28 November 2012 04:03 from mnguyen
Does your custom validation class support client-side validation?
29 November 2012 21:07 from Mikesdotnetting
@mnguyen
No it doesn't. I may well look at that in a future article.
13 December 2012 19:04 from 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.
14 December 2012 22:12 from Mikesdotnetting
@Tunde,
You would do that with simple conditional logic in a code block. It's not a job for a validator.