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.
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)
Definition and Usage The FILTER_VALIDATE_EMAIL filter validates an e-mail address.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With