ASP.NET - checking if the data in text box is a date & in mm/dd/yyyy format

Asked By SVK N on 17-Jan-12 03:28 AM
i need to check if the data entered in text box is date
if no need to display a msg
Jitendra Faye replied to SVK N on 17-Jan-12 03:31 AM
Try like this-


DateTime ursDate = DateTime.ParseExact(txtDate.Text, "MM-dd-yyyy", CultureInfo.InvariantCulture)
Jitendra Faye replied to SVK N on 17-Jan-12 03:32 AM
Try like this-


DateTime ursDate = DateTime.ParseExact(txtDate.Text, "MM-dd-yyyy", CultureInfo.InvariantCulture)
kalpana aparnathi replied to SVK N on 17-Jan-12 03:35 AM
hi,

function dateValidation()
 
{
var obj = document.getElementById("<%=txtDate.ClientID%>");
 
var day = obj.value.split("/")[0];
var month = obj.value.split("/")[1];
 
var year = obj.value.split("/")[2];
if ((day<1 || day >31) || (month<1&&month>12)&&(year.length != 4))
 
{
alert("Invalid Format");return false;
 
}
 
else
 
{
var dt = new Date(year, month-1, day);
 
var today = new Date();
if((dt.getDate() != day) || (dt.getMonth() != month-1) || (dt.getFullYear()!=year) || (dt>today))
 
{
alert("Invalid Date");return false;
 
}
 
}
 
}
dipa ahuja replied to SVK N on 17-Jan-12 03:44 AM
<asp:TextBox ID="TextBox1" runat="server" Enabled="False"></asp:TextBox>
<asp:CompareValidator runat="server" ID="req_CV_DOB" ControlToValidate="TextBox1" Display="dynamic"
Operator="DataTypeCheck" Type="Date" Text="*" ErrorMessage="Date must be in the format MM/DD/YYYY.">

SVK N replied to Jitendra Faye on 17-Jan-12 03:58 AM
is there any function as i need to validate multiple text controls for date
Riley K replied to SVK N on 17-Jan-12 04:55 AM


For that it is better to use Custom Validator

<asp:Textbox runat="server" ID="TextBox1" />
<asp:CustomValidator runat="server" ControlToValidate="TextBox1" ErrorMessage="Date was in incorrect format" OnServerValidate="CustomValidator1_ServerValidate" />
 
codebehind
 
protected void CustomValidator1_ServerValidate(object sender, ServerValidateEventArgs e)
{
  DateTime d;
  e.IsValid = DateTime.TryParseExact(e.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
}

If you want to allow several formats and only them, 
DateTime.TryParseExact(e.Value, new[] { "dd/MM/yyyy", "yyyy-MM-dd" }, CultureInfo.InvarinatCulture, DateTimeStyles.None, out d);


Regards