We help IT Professionals succeed at work.

php uk date regex not working

brillox
brillox asked
on
268 Views
Last Modified: 2012-05-11
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
 
Comment
Watch Question

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.

Author

Commented:
then I get a warning

Warning: preg_match() [function.preg-match.html]: Unknown modifier '\'
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014

Commented:
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.

Author

Commented:
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

Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.