Friday, March 30, 2012

Asp.Net - Date Validation using RegularExpressionValidator

Date validation using Asp.Net RegularExpressionValidator

Asp.Net offers the following validation controls.

RequiredFieldValidator
RegularExpressionValidator
CompareValidator
CustomValidator
RangeValidator

To validate the date, we can use the RegularExpressionValidator. This validator requires a regular expression which will validate the pattern of data entered in the control.

Open an Asp.net page and add a TextBox control, also add a RegularExpressionValidator control to validate the date entered in the TextBox

<asp:TextBox ID="txtDate" runat="server">asp:TextBox>
<asp:RegularExpressionValidator
ID="val txtDate "
runat="server"
ControlToValidate=" txtDate "
Display="None"
ErrorMessage="Enter a valid Date, Format (mm/dd/yyyy)"
SetFocusOnError="True"
ValidationExpression="^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$">
*asp:RegularExpressionValidator>

Now we have the TextBox Control and a RegularExpressionValidator control to validate the same, we should add a ValidationSummary control to handle all the validations in the page, we shall add the summary control, below the Submit button.

<asp:Button ID="cmdSave" runat="server" Text="Save"/>
<asp:ValidationSummary
ID="valSummary"
runat="server"
DisplayMode="List"
ShowMessageBox="True"
ShowSummary="False"
EnableClientScript="true"/>

Now build and run the project, enter an invalid Date in the textbox and click on the Save button.

You should get the Error message as follows.




Search Flipkart Products:
Flipkart.com

2 comments:

sAm said...

WE ARE THANKFUL TO YOU, AS IT WORKED FOR ME.. HURRAY

Anonymous said...

thank's it work..........