Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

I'm currently building a room booking system and was wondering how to check if the user has entered a date (get value) in the correct UK format of dd/mm/yyyy.

$uk_date = $_GET["date"];

For example to avoid a situation where the user types in 12/2012 or 2012 or uses the incorrect separators.

Thanks in advance!

like image 642
CJS Avatar asked Dec 16 '22 02:12

CJS


2 Answers

The 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 in your hands a DateTime object that provides lots of useful functions. One of the most important is DateTime::format which will let you get data out of the object, e.g.:

$year = $date->format('Y');
like image 180
Jon Avatar answered Feb 15 '23 11:02

Jon


Use a regex code like this:

$str = '12/12/2012';
$regex = '#^\d{1,2}([/-])\d{1,2}\1\d{4}$#';
if (preg_match($regex, $str, $m))
   echo "valid date\n";
like image 32
anubhava Avatar answered Feb 15 '23 11:02

anubhava