Wednesday, July 04, 2007

Validation controls are one of the best features that ASP.NET has to offer. They allow us to perform both client and server side validation and work very well well with the Control model that is given to us by the Web Forms model. Here I will describe how to use RegularExpressionValidator so that never again will you be searching for that email matching regular expression on all of your pages.

Usually when you use a RegularExpressionValidator you just drop it on a form (or code it by hand) and set few properties. Among them, there is the ValidationExpression. When done, it looks more or less like this:

<asp:RegularExpressionValidator runat="server" 
    ID="OnlyNormalLetters" 
    ControlToValidate="Login" 
    ErrorMessage="Login contains illegal characters" 
    ValidationExpression="[a-zA-Z]" />

As I have described in my article on the best practices of inheriting controls, it is a good idea to limit the number of times important things are repeated in the code. In case of RegularExpressionValidator, the important thing that gets repeated is of course the ValidationExpression property.

To avoid repeating the same expression on each page that requires it, it is better to create a new class that inherits from RegularExpressionValidator. In this class set the RegularExpression property to some constant string like on the following example:

public class NormalLettersValidator 
    : RegularExpressionValidator
{
    public NormalLettersValidator()
    {
        ValidationExpression = "[a-zA-Z]";
    }
}

And that's it. Using this validator is the same as using the built in one, but you don't need to provide the same ValidationExpression any more. Just register it in either web.config file or on the page and you are good to go.

Of course the example is very simple, but I hope it demonstrates a useful concept.

kick it on DotNetKicks.com