valemax
valemax

Reputation: 41

PHP - preg_match to validate date format mm/yyyy

For the check of the birthday date (format: dd/mm/yyyy) in my form I've used this code and it works fine.

if (!preg_match("/([012]?[1-9]|[12]0|3[01])\/(0?[1-9]|1[012])\/([0-9]{4})/",$date)){    
  $error[1]= "Insert a valid date";
}

But when I want to check a date with the format mm/yyyy and I use this code, it doesn't work anymore. When I try for example to put 33/2014 in my input my php validation doesn't show it as an error.

if (!preg_match("/(0?[1-9]|1[012])\/([0-9]{4})/",$date2)){  
  $error[2]= "Insert a valid date";
}

Where do I go wrong? Thank you for your help.

Upvotes: 0

Views: 1271

Answers (2)

ANZAWI
ANZAWI

Reputation: 89

Based on Tim's checkdate based solution:

The extraction of day, month and year can easily be done using explode as:

list($dd,$mm,$yyyy) = explode('/',$cnt_birthday);
if (!checkdate($mm,$dd,$yyyy)) {
        $error = true;
}

Upvotes: 0

Rangad
Rangad

Reputation: 2150

Your regex is invalid and even if it were correct you might run into some trouble with you comparison as preg_match returns in most cases an integer and not a boolean.

Simple and not so clean way:

function checkMyDate($date) {
    $components = explode('/', $date);
    if(count($components) !== 2) return false;
    return checkdate($components[0], 1, $components[1]);
}

Posssibly preffered option:

However, php has builtin functionality to work with dates. If DateTime can handle the string given you should be alright:

function checkDateByFormat($date, $format = 'n/Y') {
    $t = \DateTime::createFromFormat($format, $date);

    if($t === false) {
        return false;
    }

    return $t->format($format) === $date;
}

var_dump(checkDateByFormat('12/2014')); // true
var_dump(checkDateByFormat('13/2014')); // false
var_dump(checkDateByFormat('12/20149')); // false
var_dump(checkDateByFormat('1/e1')); // false
var_dump(checkDateByFormat('7/1982')); // true

Related to this post but taken from my own code dumpster.

Upvotes: 1

Related Questions