Using filter_var() to verify date?

前端 未结 8 1237
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:20

    Why using a heavy RegEx, while there is a native DateTime PHP-class?

    $value = 'badbadbad';
    
    try {
        $datetime = new \DateTime($value);
    
        $value = $datetime->format('Y-m-d');
    } catch(\Exception $e) {
        // Invalid date
    }
    

    Always returns the format you were expecting, if a valid datetime string was inserted.

提交回复
热议问题