The ASP.NET do and don’ts serie : episode 1 – the custom validator control

This is the first post of a serie on the ASP.NET practices.

For this serie, I get inspiration from what I see in my daily work or on the web

Don’t use custom validator when you can use an other control !

Do:

in the aspx markup


<asp:TextBox runat="server" ID="FeedURLTbx"  />

<asp:RegularExpressionValidator runat="server"
     ID="URLFormatValidator"
     ControlToValidate="FeedURLTbx"
     ValidationExpression="(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"
     Text="!"
     ErrorMessage="The URL format is not valid." />

Don’t:

in the aspx markup


<asp:TextBox runat="server" ID="FeedURLTbx"  />

 <asp:CustomValidator runat="server" ID="URLFormatValidator"
 ControlToValidate="FeedURLTbx"
 ErrorMessage="The URL format is not valid."
 OnServerValidate="ValidateURL" />

and in the aspx code behind

protected void ValidateURL(object source, ServerValidateEventArgs args)
{

System.Text.RegularExpressions.Regex myRegExp = new  System.Text.RegularExpressions.Regex(@"(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?");

args.IsValid = myRegExp.IsMatch(args.Value);
}

Why??

First because the RegularExpressionValidator is designed for string validations and it’s a non sense to do the same with another control !

Second because the CustomValidator used like here will cause a postback while the RegularExpressionValidator will generate the validation javascript and don’t cause postback.

With the RegularExpressionValidator :
good_start
good_end

With the CustomValidator :

bad_start
bad_end

I think the first reason is enough to not discuss the point !