Tutorial :PHP form validation for year



Question:

I'm using PHP to validate form input before the form data's submitted to a MySQL database.

What would be the best way to validate a form input for the year only? I have a form input where users should input a date, in the form of a year only. Obviously I can check that the input's numeric and has only 4 characters, but what would be the best way to ensure that the number inputted is a sensible number for a date?


Solution:1

That would be sufficient for simple check;

    $input = (int)$input;      if($input>1000 && $input<2100)      {        //valid      }  


Solution:2

"Sensible" is something that has to be defined by your application's business rules and/or your storage medium.

In MySQL, the DATETIME column type has a valid range of '1000-01-01 00:00:00' to '9999-12-31 23:59:59' while the TIMESTAMP has a valid range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

If you're asking the user for their birth year, then you need to be able to go back all the way to around 1900. However, if you're having them set a future appointment, then only 2009+ is valid.


Solution:3

You could just use a validation library:

http://validatious.org/learn/examples

And use min-val and max-val to limit the options. Or, even easier, just give them a combo box with valid years (html <select> tag)

Just keep in mind that valid years depends on your concept of valid. Maybe 110 years before this year could be valid if we're talking about users' ages (date(Y) - 110) but it might not be valid for some other stuff.


Solution:4

use strtotime.

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

you can do this

<?php  $year = '-1222';    $valid = true;    if (strtotime($year) === false) {    $valid = false;  }  // more of your code  ?>  


Solution:5

I would check that the date has sense in your application. For example, it is the year of birth of your users, probably any date before 1900 would be impossible, and any greater than the current year has nonsense in that context


Solution:6

This function check whether the entered year is in between current year & 100 years back.

function isValidYear($year)  {       // Convert to timestamp       $start_year         =   strtotime(date('Y') - 100); //100 Years back       $end_year           =   strtotime(date('Y')); // Current Year       $received_year      =   strtotime($year);        // Check that user date is between start & end      return (($received_year >= $start_year) && ($received_year <= $end_year));  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »