Hi,

I want sample code to validate the dates that is to be in the format YYYY-MM-DD(2011-04-21).

I had created two Textboxes to enter date and one Button Control.

The date format to be entered in the Textbox should be exactly like
YYYY-MM-DD(2011-04-21).

If user enters any other format like dd-mm-yyyy or mm-dd-yyyy or dd/mm/yyyy or mm/dd/yyyy and clicks the button it has to show error message in the label like
'Please enter valid date format'.

I'm not getting it how to do.

Can anyone please help me on this.

With Thanks,
Pavan Kumar R

Dani AI

Generated

is on the right track: use an exact parse on the server and check the boolean it returns. For WebForms, validate both fields, enforce the exact format with InvariantCulture, and ensure the range is OK before redirecting. TryParseExact will also catch impossible dates like 2011-04-31 or 2011-02-29, which answers your second question, .

using System;
using System.Globalization;

protected void btnGo_Click(object sender, EventArgs e)
{
    var fmt = "yyyy-MM-dd";
    var culture = CultureInfo.InvariantCulture;

    DateTime fromDate, toDate;
    bool okFrom = DateTime.TryParseExact(txtFrom.Text, fmt, culture, DateTimeStyles.None, out fromDate);
    bool okTo   = DateTime.TryParseExact(txtTo.Text,   fmt, culture, DateTimeStyles.None, out toDate);

    if (okFrom && okTo && toDate >= fromDate)
    {
        Response.Redirect("report.ashx?from=" + Server.UrlEncode(txtFrom.Text) +
                          "&to=" + Server.UrlEncode(txtTo.Text));
    }
    else
    {
        lblError.Text = "Please enter valid dates in YYYY-MM-DD. 'To' must be on/after 'From'.";
    }
}

For quick feedback in the browser, add a lightweight client check. First ensure the shape with a regex, then verify the calendar by constructing a Date. For ISO yyyy-MM-dd, a simple string compare is safe for range because lexical order matches chronological order.

<script>
function isIsoDate(s){
  var m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
  if(!m) return false;
  var y=+m[1], mo=+m[2], d=+m[3];
  var dt = new Date(y, mo-1, d);
  return dt.getFullYear()===y && dt.getMonth()===mo-1 && dt.getDate()===d;
}
function validateDates(){
  var from = document.getElementById('<%=txtFrom.ClientID%>').value;
  var to   = document.getElementById('<%=txtTo.ClientID%>').value;
  if(!isIsoDate(from) || !isIsoDate(to) || to < from){ alert('Please enter valid dates.'); return false; }
  return true;
}
</script>

Hook it with OnClientClick="return validateDates();" on the button. Keep the server check as the final authority.

Recommended Answers

All 4 Replies

Use DateTime.TryParseExact method,

DateTime dt;
        DateTime.TryParseExact(TextBox1.Text, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out dt);

        if (dt == DateTime.MinValue)
            Label1.Text = "Invalid";
        else
            Label1.Text = "Valid";

Hi KV(adatapost),

Thanks for Your reply.

But I'm not getting what you answered.

In my Program i have the aspx page where i created the two text box control and one button control.

If i click the button after entering the date values in the From(Date) and To(Date) Textboxes correctly ,the aspx will redirect to a new .ashx page,

Otherwise if the dates are wrong it has to show error message.

One more query is that::
If i enter the date value greater than the value of a month(i.e.if I enter date as 2011-04-31(YYYY-MM_DD) ) it has to show the error as "Invalid Date"


Thanks,

pavankumarr

The code I've posted is to validate a date. You may use Session, cookies or query string to pass values between requests.

Hi KV,

I have tried your code.
But its not validating.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.