Tuesday, March 1, 2011

html and php date input field

I am having issues trying to figure out how, to create an html input box for the date:

like this:

YYYY-MM-DD

I was wondering if there is a better method of doing this than me manually creating something like this, and then using the - separators to separate the YYYY-MM-DD.

I will be using regex to do some validation after the user has entered the date of birth to make sure that it is greater than 21.

<label for="dob">Age (YYYY-MM-DD)</label>
<input id="dateofbirth" type="text" name="age" maxlength="10"/><span>*</span><br />

Here is my regex for the date that will be inside function checkdate on the php side:

return preg_match('/(\d{4})-(\d{2})-(\d{2}, $date);

Set date such that it will only take input from users over 21. Currently this does not.
$date = '1974-12-03';

From stackoverflow
  • I would simply use a jquery date picker.

    This way you don't have to worry about the input format and you can easily get the date entered in a single format to perform validation in javascript or PHP (if you pass the date back to the server).

  • 
    if($age = strtotime($date)){ 
     if( ( date('Y',time()) - date('Y',$age ) >= 21 ){
      return true; 
     }else{ 
      return false; } 
    }else{ 
     echo 'There seems to be something wrong with your age input'; 
    }
    

    That will verify that the user is over/equal the age of 21

    Dan : I would validate that the strtotime returns and does not fail prior to completing this test so you can give the user the appropriate error message
    Brendon Sled : Right, its always best to verify any data that is coming in on a post/get var. if($age = strtotime($date)){ if( ( date('Y',time()) - date('Y',$age ) >= 21 ){ return true; }else{ return false; } }else{ echo 'There seems to be something wrong with your age input'; }
    Brendon Sled : sorry that didn't really turn out, i edited my main post instead

0 comments:

Post a Comment