ASP.NET Validation Controls – Important Points, Tips and Tricks

Posted by: Suprotim Agarwal , on 3/5/2008, in Category ASP.NET
Views: 180965
Abstract: ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions.In this article, let us see some tips and tricks that can be applied to the validation controls.
ASP.NET Validation Controls – Important Points, Tips and Tricks
 
ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions. If you are not familiar with Validation Controls in ASP.NET, here’s a recommended read for you.
In this article, let us see some tips and tricks that can be applied to the validation controls. This article is for beginner and intermediate users who have been using validation controls. There is something for everyone!!
Tip 1: Always use Page.IsValid before submitting data. Apart from the other benefits, using it prevents submitting data from old browsers that do not support javascript.
Tip 2: The display property for the ASP.NET validation controls has 3 settings: None, Static(default), and Dynamic. ‘Static outputs HTML code (related to error) at all times even when no error has occurred. So when there is more than one validation control placed next to the field, the first validation control occupies screen space even when there is no error. In case the second validation control fires an error message, the message is pushed away from the control since the first validation control is occupying screen space.
Set the ‘display’ property of a validation control to ‘Dynamic’. This property renders the error message with the attribute display:none; It helps you to display the error message next to the control .
Tip 3: To prevent validation to occur on the click of the Cancel button, set the ‘CausesValidation’ property to false
<asp:Button ID="btnCancel" Runat="server" CausesValidation="False" Text="Cancel" />
Tip 4: Use the ‘InitialValue’ property of the RequiredFieldValidator to validate controls like combobox which have a default value.
For eg: If your combobox has a default item called “--Select --“ and you want that the user should select a value other than the default value before submitting the form, then set the ‘InitialValue’ property of the RequiredFieldValidator to “--Select--“.
<asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem Value="--Select--" />
            <asp:ListItem Value="Item1" />
            <asp:ListItem Value="Item2" />
            <asp:ListItem Value="Item3" />
        </asp:DropDownList>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="DropDownList1" InitialValue="--Select--"></asp:RequiredFieldValidator>
Tip 5: A RegularExpressionValidator can be used to handle string patterns. For eg: A Name textbox that should accept a maximum of 30 characters with only alphabets, space, fullstop(.) and a ‘(apostrophe). A regularexpression like ‘^([a-zA-z.'\s]{2,30})$’ does the trick.
However when you are using Localization and using a language like Arabic, you have to often provide for validating characters in a different dialect. You can solve this using the following technique:
- In the Resource.resx file, create a resourcekey called ValidName giving it a value of ^([a-zA-z.'\s]{2,30})$
- In the Resource.ar-EG.resx file, use the same key but with a diff value ^([
\u0600-\u06FF.'\s]{2,30})$
Use it in your page using the following way. Observe the bold text:
  
<asp:RegularExpressionValidatorID='regEVFname' runat='server'ControlToValidate
='txtName'
Display='Dynamic'ErrorMessage
='Invalid’
ValidationExpression
='<%$ Resources:Resource, ValidName %>'SetFocusOnError='True'></asp:RegularExpressionValidator>
 
When the user selects English, he can enter only A-Za-z. Similarly for Arabic, he can enter only the Arabic characters and not English.
Tip 6: The validation controls provide both Server and Client Side validation. To turn off client-side validation, set the ‘EnableClientScript = false’
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" Runat="server"
   Text="Error" ControlToValidate="TextBox1" EnableClientScript="false"/>
Tip 7: Use CompareValidator to validate date with format of "dd/MM/yyyy".
The validator uses the CultureInfo object of the thread to determine date format. So what you need to do is to set the desired culture format in the Page directive
 <%@ Page culture="your culture" %>
This tip was shared by PeterBlum in the asp.net forums. By the way, Peter has an amazing suite of data entry and validation controls on his site at a reasonable price.
Tip 8: Instead of the textual error message, you can even add an image or sound to your validator control. The Text and Error Message property accepts HTML tags.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
<asp:RequiredFieldValidator ControlToValidate="TextBox1" EnableClientScript="false" ID="RequiredFieldValidator1" runat="server" Text="<bgsound src='C:\Windows\Media\Windows Error.wav'>"></asp:RequiredFieldValidator>
Just make sure that the EnableClientScript="false" when you want a sound instead of a text message.
Tip 9: If you have two set of forms (eg: Login and Registration) in a single page and want to keep the validation of the two groups separate, use ‘ValidationGroups’. All you need to do, is to specify a common group name for a set of controls that you want to validate separately.
<div>
            <asp:TextBox ID="TextBox1" ValidationGroup="Group1" runat="server"></asp:TextBox>
            <br />
            <asp:RequiredFieldValidator ControlToValidate="TextBox1" ValidationGroup="Group1" ID="RequiredFieldValidator1" runat="server" Text="Error"></asp:RequiredFieldValidator>
            <asp:Button ID="Button1" runat="server" ValidationGroup="Group1" Text="Button" />
        </div>
        <br />
        <br />
        <div>
            <asp:TextBox ID="TextBox2" ValidationGroup="Group2" runat="server"></asp:TextBox>
            <br />
            <asp:RequiredFieldValidator ControlToValidate="TextBox1" ValidationGroup="Group2" EnableClientScript="false" ID="RequiredFieldValidator2" runat="server" Text="Error"></asp:RequiredFieldValidator>
            <asp:Button ID="Button2" runat="server" ValidationGroup="Group2" Text="Button" />
        </div>       
Tip 10: Other validator controls like CompareValidator, RangeValidator etc. do not provide a way to detect if the field is blank or required. The only way is to do this is to add a RequiredFieldValidator along with the other validator controls.
However one exception being the CustomValidator which provides a property called ‘ValidateEmptyText’. Just set it to true and it validates the field even if the user has kept the field blank.
Tip 11: If you want your validation error message to appear in the ‘ValidationSummary‘ control, then set the ‘ErrorMessage’ property on that validation control. Also, setting 'ShowMessageBox = true' on the ValidationSummary enables you to display a popup alert.
Tip 12: In order to create a CustomValidationControl you have to derive from the 'BaseValidator' class and implement the 'EvaluateIsValid()' method.
Tip 13: In case of an error, the validation controls allow you to set focus on a control in error using the ‘SetFocusOnError’ property.
<asp:RequiredFieldValidator SetFocusOnError="true" ControlToValidate="TextBox1" ID="RequiredFieldValidator1" runat="server" Text="Error!!"></asp:RequiredFieldValidator>
 
I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by aayan on Thursday, March 6, 2008 8:27 AM
can u please provide a complete refrel books of c-sharp and asp.net for free download
Comment posted by Kamran shahid on Wednesday, April 2, 2008 5:31 AM
Very Nice
Comment posted by good on Wednesday, April 9, 2008 10:07 AM
send me .net intriew questions
Comment posted by Suprotim Agarwal on Thursday, April 10, 2008 12:58 AM
Hi Good, .NET Interview questions are available at
http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=58
Comment posted by madan mohan on Monday, April 21, 2008 5:31 AM
Thanks a lot to giving us clearly about validations but only the thing is You didn't explained about the display property of validation control clearly can you please give some example for that. If tell that it will be so easy..
Thank you,
Yours,
madan
        
Comment posted by Muhammad Imran on Saturday, April 26, 2008 1:23 AM
Hi

This is very good and informative article regarding validators control
Thanks

Regards
http://dotnetclassic.com
Comment posted by ToomTam on Saturday, April 26, 2008 4:03 AM
So Cool. Thank a lot
Comment posted by Shail on Saturday, April 26, 2008 11:44 PM
Nice Article. Somethings are very good to know :)
Comment posted by varnar on Monday, April 28, 2008 8:28 AM
ya its really excellent
Comment posted by Mohamed Razak on Monday, April 28, 2008 1:07 PM
Very good article. Your previous article (about calling server side methods from client side) was also excellent.
Comment posted by om on Monday, April 28, 2008 2:36 PM
Very nice article. Thanks.
Comment posted by om on Monday, April 28, 2008 2:37 PM
Very nice article. Thanks.
Comment posted by madan on Tuesday, April 29, 2008 1:37 AM
i need to know one thing actually im taking two validations to one control as required field validator and comapare validatore in that while executoin second one is firing and first one is in off position but fist one is taking place. i tried that dynamic in place of static for both but it is not working. i dont know proper way to do it . can any one please tell me that
Comment posted by Ravi on Tuesday, April 29, 2008 5:04 AM
Hi .. Thanks for the article. It is one of the best I read so far. really useful
Comment posted by raghu on Tuesday, April 29, 2008 6:09 AM
Static and dynamic display tip is good .I never cared for those all these years.
Comment posted by Ric on Wednesday, April 30, 2008 10:15 PM
Does all these validations occour on client side or server side??
Comment posted by Rishi Saxena on Thursday, May 1, 2008 4:04 AM
Just to add to the Listing: To limit number of characters allowed in a multiline textbox use following syntax.
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtRmks"
        ErrorMessage="Not More Than 500 Characters are allowed !" ValidationExpression="[\s\S]{0,500}" Display="Dynamic"></asp:RegularExpressionValidator>
Comment posted by Siju George on Friday, May 2, 2008 7:18 AM
Nice article. Really helped me!!!
Comment posted by Suprotim Agarwal on Saturday, May 3, 2008 7:28 AM
Thanks for the tip Rishi.
Comment posted by gaurav kumar on Wednesday, May 7, 2008 4:37 AM
Nice article. Really helped me!!!
Comment posted by wissam ajamy on Saturday, May 17, 2008 2:30 AM
Hello,
I'm trying to find all controls of type validator in a user control from outside the user control (on post back event), then if the Display property of any validator is set to None i cant see or access this validator otherwise it works fine

foreach (object item in userControl.Controls)
      if (item.GetType().IsSubclassOf(typeof(BaseValidator)))
          {//do sth}

Did you ever face such case before?
Comment posted by Nripin Babu on Thursday, May 29, 2008 1:51 AM
I love this! Good work!
Comment posted by nestor on Friday, May 30, 2008 6:31 PM
thanks for share this article¡¡¡
Comment posted by jayasree on Saturday, May 31, 2008 11:19 AM
hi,
can u send me,.net(c#,asp.net n vb.net) material n interview based questios?
Comment posted by Suprotim Agarwal on Sunday, June 1, 2008 1:34 AM
Gaurav, Nripin, Nestor: Thanks for your comments

Wissam: Are you still facing the issue?

Jayasree: For Interview questions, check this link

http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=58
Comment posted by Vandana Shrivastava on Thursday, June 5, 2008 5:32 AM
The Tips for validation controls are really very good
Comment posted by Aiswarya on Wednesday, June 11, 2008 2:49 AM
its nice.
Comment posted by pradeep on Wednesday, June 25, 2008 2:48 AM
This article is very good with brief point wise explanation.
Comment posted by gonga on Friday, June 27, 2008 5:33 AM
hey all, I'm quite new to ASP.net. I'd like to have a common RegularExpressionValidator for all places where the Postal code is entered in my Webpage.... so that I don't need to repeat the expression validation for the postal code whenever I need it. Calling a class that makes it would be a nice Idea..
Thanks in advance
Comment posted by Subhashini on Friday, July 25, 2008 3:25 PM
This article is really and revealing the very important properties. I am a starter in ASP.NET Can you please share the websites with ASP.NET questions, easy to understand websites like this article :)
Comment posted by Suprotim Agarwal on Sunday, July 27, 2008 7:43 AM
Suhasini: You can find some asp.net FAQ's over here:
http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=58

Other ASP.NET articles can be found over here:
http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=54
Comment posted by kjkl on Wednesday, August 6, 2008 8:46 AM
jikjkl
Comment posted by Raj on Tuesday, August 12, 2008 1:33 AM
Nice one!
Comment posted by Willie Roberts on Wednesday, September 3, 2008 5:07 PM
Nice summary. Finally figured out how to use Resource Files correctly
Comment posted by satya on Tuesday, September 23, 2008 5:08 AM
nice and helpful
Comment posted by Sunny on Wednesday, October 15, 2008 9:30 AM
nice article and things to take care while programming. Keep Posting.
Comment posted by dgd on Tuesday, October 21, 2008 5:02 AM
ghjghjghjghj
Comment posted by usmi on Monday, October 27, 2008 7:33 AM
good
Comment posted by Jay Khatri on Wednesday, August 12, 2009 6:27 AM
Very Nice article, I had a problem from couple of days that validation control validates the fields but not showing the error message. I researched and found that I am doing display:none in css for div which contains this validator control. and I put it back to block when user clicks the button. teh entire div get displayed. But while validating control dont work. I think there is some clash between the way that validator gets shown and my external display:none.

I hope u can solve my problem.

Thanks

Jay
Comment posted by Suprotim Agarwal on Saturday, August 15, 2009 2:42 AM
Jay: Why do you do it explicitly. As mentioned in the article - Set the ‘display’ property of a validation control to ‘Dynamic’. This property renders the error message with the attribute display:none
Comment posted by anupam on Thursday, March 18, 2010 7:09 AM
thanks........a real good one
Comment posted by Sandeep on Tuesday, April 20, 2010 4:53 PM
Good article.
I found another good article that explain about various Validation controls
Have a look http://aspdotnethacker.blogspot.com/p/aspnet-controls.html
Comment posted by ekta on Saturday, April 2, 2011 4:22 AM
it's  gud in xam's to refer so nice article
Comment posted by sasidhar on Monday, August 8, 2011 2:37 PM
Thanks...........nice article.
can u explain how the validation occur in server side, when we set 'EnableClientScript="false"'.
Comment posted by Arvind on Sunday, October 16, 2011 8:50 AM
asp.net validation controls
Comment posted by Ankit Singh on Monday, January 9, 2012 4:04 AM
Very informative post. It's really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about Validating FileUpload control for specific file type and required field, for more details of this post check out this link...

http://mindstick.com/Articles/7d72a758-52bc-4242-922f-6b3914895d92/default.aspx?Validating+FileUpload+control+for+specific+file+type+and+required+field.

Thanks
Comment posted by nisha on Thursday, February 9, 2012 3:28 AM
nice, very good experience of learning the validation using this article and better understand to me with the help of this topic
Comment posted by Satya on Tuesday, July 3, 2012 12:06 AM
Superb Article..
Simple things can learn faster with Good understanding..
Comment posted by Mohammad AbuTarique on Wednesday, February 27, 2013 6:41 AM
nice
Comment posted by yagdeep on Sunday, April 14, 2013 1:50 AM
please explain benefits of validation controls with examples to understand more easily........... thank you
Comment posted by Aamir Ghanchi on Thursday, May 23, 2013 5:10 PM
Good tips! Great Job!
Comment posted by Will on Monday, April 7, 2014 5:31 PM
Thanks. This was as good, concise article. It covers a lot of details.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel