Creating a function in php that checks that the value gets in the order dd / mm / yyy

I am currently building a room reservation system and wondering how to check if the user is entered on the date (get the value) in the correct UK format dd / mm / yyyy.

$uk_date = $_GET["date"]; 

For example, to avoid a situation where the user enters data in 12/2012 or 2012 or uses the wrong delimiters.

Thanks in advance!

+4
source share
4 answers

Best would be DateTime::createFromFormat :

 $date = DateTime::createFromFormat('d/m/Y', $uk_date); $errors = DateTime::getLastErrors(); if($errors['warning_count'] || $errors['error_count']) { // something went wrong, you can look into $errors to see what exactly } 

If the parsing is successful, then you have a DateTime object that provides many useful functions. One of the most important is DateTime::format , which allows you to get data from an object, for example:

 $year = $date->format('Y'); 
+4
source

Use regex code as follows:

 $str = '12/12/2012'; $regex = '#^\d{1,2}([/-])\d{1,2}\1\d{4}$#'; if (preg_match($regex, $str, $m)) echo "valid date\n"; 
+3
source

Try this feature:

 public static function CheckValidDate($sDate) { $sDate = str_replace('/', '-', $sDate); preg_match('/^(\d{2})-(\d{2})-(\d{4})$/', $sDate, $xadBits); if ($xadBits) return checkdate($xadBits[2], $xadBits[1], $xadBits[3]); else return false; } 

Go to the link: http://php.net/manual/en/function.checkdate.php

Thanks for the comment @SalmanA

+3
source

Try this regex:

 $pattern = '|^[\d]{,2}/[\d]{,2}/[\d]{,4}$|is'; if (preg_match($pattern, $date, $match)) { echo 'ok!'; } 
+2
source

Source: https://habr.com/ru/post/1402215/


All Articles