Reputation: 101
I have some kind of problems with regular expressions, this one checks if my date is in mm/dd/yyyy format:
/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d+$/
I need the same one but checking if the date is like dd/mm/yyyy (european date)
I got no clue about how this stuff work, I've checked some guides but I can't figure out how to edit this one.
Any help would be appreciated =)
Upvotes: 0
Views: 80
Reputation: 331
^(0[1-9]|1[012])
matches the month component (0[1-9]|[12][0-9]|3[01])
matches the day of month component(19|20)\d\d
matches the year component[- /.]
just matches a -, space, /, or .This means that your regex will also match e.g. 12-31/2013
I think that the +
at the end of the regex doesn't belong there - it would allow for additional digits after the year component.
The same regex restructured to match dd/mm/yyyy
would look like this:
^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d$
Upvotes: 0
Reputation: 2686
Have a careful look at your expression: you will see that it is divided into three parts: the first part (0[1-9]|1[012])
matches months (from 01 to 12), the second part (0[1-9]|[12][0-9]|3[01])
matches days (from 01 to 31), while a last part (19|20)\d\d+
matches years (from 1900 up). Finally, [- /.]
matches your separators (-
or
.
) and ^
and $
match string beginning and string end, respectively.
I want to add two more observations:
.
is \
rather than /
(19|20)\d\d+
: this will maths 1900
but will also match 190000 (because of the + sign).Given this, I would change your regexp as follows:
^(0[1-9]|[12][0-9]|3[01])[- \.](0[1-9]|1[012])[- \.](19|20)\d{2}$
note however that this regexp will match also non-valid dates as for example 30th of February.
If you need something more accurate have a look here: Regex to validate date format dd/mm/yyyy
Upvotes: 1
Reputation: 3172
Example for php
09-02-2015
/**
* Validates the date
* @param string $date
* @return boolean
*/
protected function checkDate($date)
{
if (preg_match('@^[0-9]{2}-[0-9]{2}-[0-9]{4}$@', $date)) {
return true;
} else {
return false;
}
}
for 09/02/2015
/**
* Validates the date
* @param string $date
* @return boolean
*/
protected function checkDate($date)
{
if (preg_match('@^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$@', $date)) {
return true;
} else {
return false;
}
}
Upvotes: 0