Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using filter_var() to verify date?

Tags:

php

filtering

I'm obviously not using filter_var() correctly. I need to check that the user has entered a valid date, in the form "dd/mm/yyyy".

This simply returns whatever I passed as a date, while I expected it to return either the date or 0/null/FALSE in case the input string doesn't look like a date:

$myregex = "/\d{2}\/\d{2}\/\d{4}/";
print filter_var("bad 01/02/2012 bad",FILTER_VALIDATE_REGEXP,array("options"=>array("regexp"=> $myregex)));

If someone else uses this function to check dates, what am I doing wrong? Should I use another function to validate form fields?

Thank you.

like image 721
Gulbahar Avatar asked Dec 06 '12 14:12

Gulbahar


People also ask

What is Filter_var function in PHP?

PHP | filter_var() Function The filter_var() function filters a variable with the specified filter. This function is used to both validate and sanitize the data. Syntax :- filter_var(var, filtername, options)

What is FILTER_ VALIDATE_ email?

Definition and Usage The FILTER_VALIDATE_EMAIL filter validates an e-mail address.


2 Answers

You can check date by using this function:

function is_date_valid($date, $format = "Y-m-d"){
    $parsed_date = date_parse_from_format($format, $date);
    if(!$parsed_date['error_count'] && !$parsed_date['warning_count']){
        return true;
    }

    return false;
}

How to use it:

$is_valid = is_date_valid("2021-8-1"); // it will return boolean.

Note: You can change the format of the date via pass the format in the second parameter.

like image 91
Mohamad Hamouday Avatar answered Oct 05 '22 02:10

Mohamad Hamouday


A simple and convenient way to verify the date in PHP is a strtotime function. You can validate the date with only one line:

strtotime("bad 01/02/2012 bad"); //false
strtotime("01/02/2012"); //1325455200 unix timestamp
like image 25
Cmyker Avatar answered Oct 05 '22 04:10

Cmyker