0

I am trying to validate a text field for valid date (MM/DD/YYYY) I have not done this validation before and wondering if it is easy to achieve through regular expression validator or through Jquery?

Example would be greatly appreciated.

1 Answer 1

1

The easiest way in ASP.Net to validate an input text box to insure that is has a valid date is to use an ASP.Net CompareValidator. Set the Operator to "DateTypeCheck" and the Type to "Date", and the form submission will only go thru if the input text box contains a valid date.

<asp:TextBox ID="tbInput" runat="server" />
<asp:CompareValidator ID="cmpTest" EnableClientScript="true" ControlToValidate="tbInput" 
Type="Date" Operator="DataTypeCheck" runat="server"/>

See here for more details: http://msdn.microsoft.com/en-us/library/ad548tzy(v=vs.71).aspx

To insure that the date is in the past, use a ASP.Net Range validator, and programmatically set the MaximumValue and MinimumValue attributes to the max and min date your want:

<asp:RangeValidator ID="cmpTest2" ControlToValidate="tbInput" Type="Date" runat="server" ErrorMessage="Date must be in past" />

protected void Page_Init(object sender, EventArgs e)
{
    cmpTest2.MaximumValue = DateTime.Now.Date.ToString("MM-dd-yyyy");
    cmpTest2.MinimumValue = DateTime.Now.AddYears(-100).ToString("MM-dd-yyyy");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Joe! How can I ensure that it is valid date in the past and not in future.
You can use a RangeValidator. See the edits to my post above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.