0

As you may know, php date will return a valid date on these dates:

year-04-31

year-06-31

year-09-31

I have read other SO thread here about the non existed date, but this thread did not solve my problem. My goal is to prevent php to automatically let these date convert to next day. For example, if user input date 2018-04-31, the system will prompt an error.

$value = '2018-06-31'; // assume user input this date
if(date is 04-31, 06-31 or 09-31) // i have no idea what to put here
  echo 'wrong date, please enter again';

EDIT

someone actually posted this question as duplicate for for this thread in SO...which part it says something about 4-31, 6-31, 9-31? please dont simply mark this as duplicate, make your comparison between my question and the others before mark. thank you

LearnProgramming
  • 814
  • 1
  • 12
  • 37

3 Answers3

1

Try the following

<?php

$date = '2018-06-31';


function checkIsAValidDate($date){
    return (bool)strtotime($date) && date("Y-m-d", strtotime($date)) == $date;
}

if(checkIsAValidDate($date) == 1){
    echo 'valid';   
}else{
    echo 'not valid';
}

?>

This will validate the format, and that the date is real. IE, there are only 30 days in the month of June.

0

strtotime will return FALSE in case it cannot convert string to timestamp. So you can try:

if (strtotime('<your date time string here>') === false) {
   // TODO.
}

----- EDIT ----- Thanks to @Nick.

strtotime may wrong in some case as '02-30'. So I suggest another solution:

$date = explode('-', '<date time string>');
if (checkdate($date[1], $date[2], $date[0]) {
    // TODO
}
Nghi Ho
  • 463
  • 1
  • 6
  • 18
-2

I guess you don't to allow users to input 31st when the month is of 30 days. In that case why don't you simple use a datepicker? Instead of allowing users to enter the date make them choose one. If you are scared about editing after the date is chosen then use a javascript function to disable text input in the filed and allow only clicks which makes datepicker to appear.

  • The server always has to do input validation. There's no client-side way to enforce valid values. – deceze Oct 30 '18 at 05:30