Using filter_var() to verify date?

前端 未结 8 1311
Happy的楠姐
Happy的楠姐 2021-01-12 01:58

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 p

8条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 02:27

    The better solution is posted by @baba, but the code posted doesn't work fine in certain conditions.

    For example if you try to validate this date "2019-12-313";

    $date = date_parse("2019-12-313");
    

    the function returns this array:

    Array
    (
        [year] => 2019
        [month] => 12
        [day] => 31
        [hour] => 
        [minute] => 
        [second] => 
        [fraction] => 
        [warning_count] => 0
        [warnings] => Array
            (
            )
    
        [error_count] => 1
        [errors] => Array
            (
                [10] => Unexpected character
            )
    
        [is_localtime] => 
    )
    

    so, if you perform the command:

    checkdate($date['month'], $date['day'], $date['year']);
    

    checkdate will returns a true value because the value of $date['day'] is 31 instead of 313.

    to avoid this case maybe you have to add a check to the value of $date['error_count']

    the @baba example updated

    $date = "2019-12-313";
    $date = date_parse($date); // or date_parse_from_format("d/m/Y", $date);
    if ($date['error_count'] == 0 && checkdate($date['month'], $date['day'], $date['year'])) {
        // Valid Date
    }
    

提交回复
热议问题