i have a form that asks for date input (field is date type in mysql). i want user to input date in YYYY-MM-DD format. if the input is wrong i want them to get a message saying "invalid date format" and nothing is updated on my database. how should i do this?

i tried:

if (!preg_match ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $_POST['mydate']))  {

but this translates the input into YYYY-MM-DD but they do not get any warning! when they input, say ghghgh it turns out to be 0000-00-00 on mysql and when they put 5-8-04 (meaning may 8, 2004) it turns out to be 2005-08-04!

help please!

    Try this instead:

    if (!preg_match ("/([0-9]{4})-([0-9]{2})-([0-9]{2})/", $_POST['mydate']))  {

    You had forgotten the pattern encloser (that's what the / is).

    -- lilleman

      hi i just used the code you posted, i thought it was working well but i noticed that when a user inputs 2004-24-12 (meanind dec. 24) the script accepts it as valid but on the sql it becomes 0000-00-00. any idea to prevent this? thanks.

        try this pattern

        "/[0-9]{4}-[01][0-9]-[0-3][0-9]/"

          I came to think of a function that you could use; [man]checkdate/man.

          $userdate = '2004-24-12';
          list($year, $month, $day) = split('-', $userdate);
          
          if( !checkdate($month, $day, $year) ) {
            // the date is not valid
          }

          Then the syntax must be YYYY-MM-DD, otherwise the date may not be accepted by checkdate().

          -- lilleman

            that worked sid 🙂 thanks. thanks too lilleman!!!! could you tell me how that worked? 😉 (explain the syntax)

              I assume that you know what the first line does. 😉
              The second line splits the date-string at each - and by using the list() function, we assign the values to three variables instead of accepting it as an array.

              The syntax for the checkdate() function is:

              bool checkdate ( int month, int day, int year)

              If the date is valid, checkdate() return true, otherwise false. Because of that, we can use it in an if statement to see if the date was valid.

              -- lilleman

                However, using [man]split[/man] is overkill in this case (as that page notes).

                  I thought that split() was faster than explode(), even though it uses a regular expression.

                  -- lilleman

                    Write a Reply...