Solved

Need help validating date YYYY-MM-DD

Posted on 2009-03-31
12
932 Views
Last Modified: 2012-06-27
looking for a regex in .Net for validating a date parameter
with following attributes
Accepts dates with format yyyy-mm-dd
date should be between (1753-01-01 and 9999-12-31)(both inclusive)

Appreciate your help.
Thanks
0
Comment
Question by:EmiliJ
  • 5
  • 3
  • 2
  • +2
12 Comments
 
LVL 65

Expert Comment

by:rockiroads
ID: 24029272
What if you formatted your date using ToString as YYYYMMDD then check to see if its >= 17530101 and <= 99991231

0
 
LVL 65

Expert Comment

by:rockiroads
ID: 24029327
date mask should be yyyyMMdd
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 24029346
if its a web application then i will recommend you to use a range validator
the sample is shown in the folowing EE link
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_22864495.html
0
 
LVL 6

Expert Comment

by:Cebik
ID: 24029377
too much code :( ?

 bool check(string s)

        {

            DateTime dt = DateTime.MinValue;

            try

            {

                DateTime.ParseExact(s, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture);

                //or try parse exact

            }

            catch (Exception ex)

            {

                return false;

            }
 

            if (dt < new DateTime(1753, 01, 01))

                return false;

            if (dt > new DateTime(9999, 12, 31))

                return false;
 

            return true;

        }

Open in new window

0
 
LVL 65

Expert Comment

by:rockiroads
ID: 24029398
an example

int iMyDate = Convert.ToInt32(dt.ToString("yyyyMMdd"));

if (iMyDate >= 17530101 && iMyDate <= 99991231)
{
    MessageBox.Show("Valid Date")
} else {
    MessageBox.Show("Invalid");
}

0
 
LVL 6

Expert Comment

by:Cebik
ID: 24029405
or that..
i know that is'n regex..

bool Check(string s)

{

    DateTime dt = DateTime.MinValue;

    bool result = DateTime.TryParseExact(s, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dt);
 

    if (!result || (dt < new DateTime(1753, 01, 01)) || (dt > new DateTime(9999, 12, 31)))

        return false;
 

    return true;

}

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 6

Expert Comment

by:Cebik
ID: 24029451
and final version..
good luck ;)

/// <summary>

/// Check range and return result and dateTime.

/// </summary>

/// <param name="s">input string</param>

/// <param name="dateTime">DateTime.MinValue if not correct!</param>

/// <returns>true or false</returns>

bool Check(string s, out DateTime dateTime)

{

    dateTime = DateTime.MinValue;

    bool result = DateTime.TryParseExact(s, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateTime);
 

    if (!result || (dateTime < new DateTime(1753, 01, 01)) || (dateTime > new DateTime(9999, 12, 31)))

        return false;
 

    return true;

}

Open in new window

0
 

Author Comment

by:EmiliJ
ID: 24029703
Thanks for all reply. actually I am developing a web service and using regex expressions for validating parameters. I wanted to be consistent and that the reason I wish to have regex to validate date ranges.

0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 24030115
can you please try my suggestion for web using range validator sample using EE
ID:24029346
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 24030120
You could use regex to perhaps check the format but your question of checking to see if its within a range, Im not sure if thats possible using regular expressions or is worth it. But you can use it to check for it to be in the format yyyyy-mm-dd

Im trying to get this expression to work but it seems to not recognise it as a valid sequence  http://www.dotnetspider.com/forum/85373-regular-expression-for-date-format-yyyy-mm-dd.aspx

And in code I have to try it out is

Regex rex = new Regex("(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])");

if (rex.IsMatch("2001-11-11").ToString())
{
    MessageBox.show("So far date in valid format");
} else {
    MessageBox.show("Date not in valid format");
}

But as I said, it is complaining about that expression in c#
0
 
LVL 6

Expert Comment

by:obrienslalom
ID: 24030303
I have the year portion of the regex validation functioning (I think).  I got a bit lazy so I didn't do the date/day validation (but I'd imagine you know how to do that).  If not, I can finish it for you.  Anyway, you can remove the ?: if you don't care where any capture groups go.

(?:(?:1[7-9](?:(?:(?<=7)(?:[5-9][3-9]))|(?:(?<=[8-9])(?:\d\d))))|(?:[2-9]\d{3}))-\d{2}-\d{2}
 

-------------------------------

Test data (* represent pass):

1752-01-01

1822-01-01  * 

1753-01-01  *

1794-01-01  *

8015-03-11  *

9999-12-31  *

10002-12-23

Open in new window

0
 
LVL 65

Accepted Solution

by:
rockiroads earned 500 total points
ID: 24030375
Ok, I couldnt get the date range in the regular expressions. Still working on it.
So a combination of regular expression and normal date range check



private bool isValidDate(String sDate)
{
      bool isValid = false;

      //yyyy-mm-dd format
      string pattern =  "\\d{4}([/-])\\d{1,2}\\1\\d{1,2}";
                  
      Regex rex = new Regex(pattern);

      if (rex.IsMatch(sDate))
      {
            try
            {
                  DateTime dt = DateTime.ParseExact(sDate,"yyyy-MM-dd",null);

                  int iMyDate = Convert.ToInt32(dt.ToString("yyyyMMdd"));

                  if (iMyDate >= 17530101  && iMyDate <= 99991231)
                  {
                        isValid = true;
                  }
            }
            catch (Exception)
            {
            }
      }

      return isValid;
}


and sample usage

String sDate = "2001-12-31";
bool isValid = isValidDate(sDate);

if (isValid)
{
      MessageBox.Show(sDate + " is valid");
}
else
{
      MessageBox.Show(sDate + " is not valid");
}
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

914 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now