kalls
kalls

Reputation: 2855

Regular expression or Jquery to validate a ASP.NET textbox for valid date and in the past

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.

Upvotes: 0

Views: 1011

Answers (1)

Joe Alfano
Joe Alfano

Reputation: 10289

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");
}

Upvotes: 1

Related Questions