I’m not a big fan of ASP.NET WebForms, and one of my pain points is form validation. It seems a bit heavy-handed and clumsy compared to, say, Dynamic Data or MVC. Generally, it’s adequate.
To validate that a textbox is required is easy enough, just use a RequiredFieldValidator. To validate the text is in some specific format seems easy enough too, just use RegularExpressionValidator. But the “gotcha” that may not be immediately apparent is that using the RegularExpressionValidator as is requires you to violate DRY, since you must specify the ValidationExpression each time you use it. With this, you get all the standard pitfalls of DRY, including the possibility of a phone number formatting on Form1.aspx being totally different than the phone number formatting on Form2.aspx. So, wat do?
Here’s what I did: create a more specific implementation of RegularExpressionValidator called PhoneValidator
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Whatever
{
[ToolboxData("<{0}:PhoneValidator runat=\"server\" />")]
public class PhoneValidator : RegularExpressionValidator
{
public PhoneValidator()
{
ValidationExpression = @"^([\(]{1}[0-9]{3}[\)]{1 ... $";
}
}
}
And now you can use PhoneValidator just as you would RegularExpressionValidator, except the ValidationExpression only exists in one place for consistency and ease of change. Don’t forget to register the assembly that the above class is in on your page:
<%@ Register assembly="WhateverAssembly" namespace="Whatever" tagprefix="MyValidator" %>
(Or you could register it in your web.config for use in the whole app). Once it’s registered, just do this (it should appear in intellisense as well):
<MyValidator:PhoneValidator ControlToValidate="txt_phone_number" runat="server" />