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\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?" 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\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"); 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 :
With the CustomValidator :
I think the first reason is enough to not discuss the point !