Using filter_var() to verify date?

前端 未结 8 1231
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:15

    $myregex = '~^\d{2}/\d{2}/\d{4}$~';
    

    The regex matched because you just require that pattern anywhere in the string. What you want is only that pattern and nothing else. So add ^ and $.

    Note that this still doesn't mean the value is a valid date. 99/99/9999 will pass that test. I'd use:

    if (!DateTime::createFromFormat('d/m/Y', $string))
    

提交回复
热议问题