Link to home
Start Free TrialLog in
Avatar of Lance_Frisbee
Lance_FrisbeeFlag for United States of America

asked on

RegularExpressionValidator (Date)

Hi, I am looking for code that will set a regular expression validator to validate dates in this format: mm/dd/yyyy. I have this code already in: \d{2}/\d{2}/\d{4}

I need to have it accept (m or mm) and (d or dd). So if it was March 1st, it would be acceptable to write 3/1/2004 and not have to type out 03/01/2004. Minor i know, but thats what the boss wants.

Thanks for your responses.

Lance
Avatar of eternal_21
eternal_21

What about \d{1, 2}/\d{1, 2}/\d{4} ?
Avatar of Lance_Frisbee

ASKER

Nope, that doesn't work.
It's probably something stupidly simple like that though, and i am just overlooking it.
ASKER CERTIFIED SOLUTION
Avatar of eternal_21
eternal_21

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you eternal.
For completeness, I would use a method like this:

    bool IsValidDate(string dateString)
    {
      if(System.Text.RegularExpressions.Regex.Match(dateString, @"\d{1,2}/\d{1,2}/\d{4}").Success)
        try
        {
          DateTime.ParseExact(dateString, "dd/mm/yyyy", System.Globalization.CultureInfo.InvariantCulture);
          return true;
        }
        catch
        {
          return false;
        }
      else
        return false;
    }

Glad I could help, Lance.
There is an error in the above method!  Replace with:

### C#.NET ###

    bool IsValidDate(string dateString)
    {
      // Use Regex first to check for obvious non-matches
      // (eg: text, year in the wrong position).
      if(System.Text.RegularExpressions.Regex.Match(dateString, @"^\d{1,2}/\d{1,2}/\d{4}$").Success)
        try
        {
          // Then try to parse it into a DateTime to be sure
          // (makes sure that user cannot enter 99/01/2004).
          string[] allowedFormats;
          allowedFormats = new string[] {
                            "MM/dd/yyyy",
                            "M/dd/yyyy",
                            "MM/d/yyyy",
                            "M/d/yyyy"
                          };
          DateTime.ParseExact(dateString, allowedFormats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);          
          return true;
        }
        catch
        {
          return false;
        }
      else
        return false;
    }

###
Thank you eternal... i've already edited it :) i ended up with another validator. then parsing it to datetime

the validator ended up being: ([1-9]|1[012]||0[1-9]|1[012])[- /.]([1-9]|[12][0-9]|3[01]||0[1-9]|[12][0-9]|3[01])[- /.](20)\d\d