tags:

views:

88

answers:

3

Hi

Please help me with a regular expression to validate the following format

dd/mm

This is for validating a Birthday field and the year is not required.

Thanks

A: 
new Regex(@"^\d{2}/\d{2}$")

or:

new Regex(@"^\d\d/\d\d$")

\d represents a digit, and {2} specifies that it must be repeated twice.

To check if it's a real date, use DateTime.TryParseExact:

DateTime date;
bool valid;
valid = DateTime.TryParseExact("00/00", "dd/MM", null, DateTimeStyles.None, out date); // false
valid = DateTime.TryParseExact("30/02", "dd/MM", null, DateTimeStyles.None, out date); // false
valid = DateTime.TryParseExact("27/02", "dd/MM", null, DateTimeStyles.None, out date); // true

However, this will not handle leap years properly. Probably the best solution is to ask for the year of birth after all.

Matthew Flaschen
in this regular expression 00/00 is a valid date
Itay
@Itay, she asked about validating the format, not that it was a real date. To check if it's a real date, it's best just to use [`DateTime.TryParse`](http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx).
Matthew Flaschen
Thanks Matthew ... Its She not her ;-)
swapna
How can I validate date as well. For example .. 30/02 should be false.
swapna
You cannot validate a date if you do not have the year because you cant tell if February 29 is valid or not
Itay
yeah yeah .. I know... 29 can be an exemption.
swapna
A: 
^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])$

but this one will allow for example 30/02

Itay
+2  A: 
bool foundMatch = false;
foundMatch = Regex.IsMatch(SubjectString, 
    @"^(?:
     (?:[12][0-9]|0?[1-9])/(?:0?2|Feb(?:ruary)?)
     |
     (?:30|[12][0-9]|0?[1-9])/
      (?:
       (?:0?[469]|11)
       |
       Apr(?:il)?|June?|Sep(?:tember)?|Nov(?:ember)?
      )
     |
     (?:3[01]|[12][0-9]|0?[1-9])/
      (?:
       (?:0?[13578]|1[02])
       |
       Jan(?:uary)?|Mar(?:ch)?|May|July?|Aug(?:ust)?|Oct(?:ober)?|Dec(?:ember)?
      )
     )$",  
    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

will match valid days/months. It will always match Feb 29 since it doesn't know the year.

By the way, I made this regex using RegexMagic (much too tedious to do this manually - another sign that this is rather a job for a date/time parser).

Tim Pietzcker
Thanks Tim. How easy will it be to change the format from mm/dd to mm/month i.e 02/febraury etc?
swapna
Now both variants are supported.
Tim Pietzcker