Link to home
Start Free TrialLog in
Avatar of brillox
brilloxFlag for United Kingdom of Great Britain and Northern Ireland

asked on

php uk date regex not working

Hi experts

I am trying to validate uk date input in a pHP form  by using

case 'ukdate':
{
$bret= $this->test_datatype($input_value,"/^(0[1-9]|[12][0-9]|3[01])[- ^\/.](0[1-9]|1[012])[- ^\/.](19|20)\d\d$/");
if(false == $bret)
{
$default_error_message = sprintf(E_VAL_UKDATE_CHECK_FAILED,$variable_name);
}
break;
}

the test_datatype function is working with other validations, so I assume that the regex is not properly written. I found it by googling as I do not have knowledge of regex at all  :-)

basically does not matter what I type, the test_datatype function return always true in this case

I think the issue is with \/ but I cannot figure it out what to change.
The format I am looking to  validate is dd/mm/yyyy
 
Avatar of brutaldev
brutaldev
Flag of South Africa image

The slashes in the front and that back of that reg ex string look wrong. Take the slashes out and the date format you've specified is matched.

It should look like this "^(0[1-9]|[12][0-9]|3[01])[- ^\/.](0[1-9]|1[012])[- ^\/.](19|20)\d\d$"

To test it use an online tool like NRegex.
Avatar of brillox

ASKER

then I get a warning

Warning: preg_match() [function.preg-match.html]: Unknown modifier '\'
ASKER CERTIFIED SOLUTION
Avatar of brutaldev
brutaldev
Flag of South Africa image

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
To test for a date, you should use strtotime() instead of regex.  See the article here:
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

It's really this easy (no regex debugging required):

if (!$timestamp = strtotime($date_time_input_string)) echo "$date_time_input_string IS A BOGUS DATE";
For more clarification, you only need to the # (or some other valid character not in your regex) when you are in PHP. If you want to test the regex with other tools you need to only take what's between them.
Avatar of brillox

ASKER

Thanks brutaldev, it worked. I did not know that i could use any delimiter; I thought / was the only one

Hi Ray, I will take into account also your suggestion