Page 1 of 1

Validating a year from form input

Posted: Sat Jan 20, 2007 11:39 am
by me!
I am trying to validate a year that a user inputs from a form. The format MUST be in "2007" format so I came up with the code here. But it is not working. :cry:

Code: Select all

//Check experation date
		if ("$date_override" == '1')
			{
				if(trim("$pn_duesexdate") =='' || strlen(trim("$pn_duesexdate")) == 4)
					{
					$error_msg.="<li>The experation year is invalid.</li>";
					$error_12 = ' class="formerror"'; 
					}else{
							// now check if year is a valid format
							if(!ereg("([0-9]{4})", "$pn_duesexdate")) 
								{
								$error_msg.="<li>The experation year is invalid.</li>";
								$error_12 = ' class="formerror"'; 
								}
							}
			}

Posted: Sat Jan 20, 2007 11:46 am
by John Cartwright
I don't see anything particularly wrong, although it may be shorted to simply:

Code: Select all

if (ctype_digit($source) && strlen($source) == 4)
{
   // valid
}
Better yet,

Untested (I'm not the best at regex btw ;))

Code: Select all

preg_match('#^(19|20)/d{2}$#', $source);

Posted: Sat Jan 20, 2007 11:54 am
by Z3RO21
If it is coming from a form you could simple use a select box that has the dates predefined within it. This way the data you know will be a certain format, and you can always check to see if it is not.

Posted: Sat Jan 20, 2007 12:14 pm
by feyd
It must be validated just the same at any rate, so the form itself doesn't really matter so much. ;)

Posted: Sat Jan 20, 2007 3:54 pm
by me!
This is the part that is not working, it always comes back with the error.

In the tests $pn_duesexdate = 2008

Code: Select all

// now check if year is a valid format
                   if(!ereg("([0-9]{4})", "$pn_duesexdate"))
                                    {
                                    $error_msg.="<li>The experation year is invalid.</li>";
                                    $error_12 = ' class="formerror"';
                                    } 

Posted: Sat Jan 20, 2007 3:58 pm
by John Cartwright
I've already given two alternatives to ereg(), which is slower than both alternatives as well as (if memory serves) will be deprecated in the next major php version anyways..

Now that I am looking at your code again, try re-arranging your logic flow.

Your code can be simplified into

Code: Select all

if ($date_override == '1')
{
   $pn_duesexdate = trim($pn_duesexdate);
   
   if ((empty($pn_duesexdate)) || !ereg("([0-9]{4})", $pn_duesexdate))
   {
      $error_msg.="<li>The experation year is invalid.</li>";
      $error_12 = ' class="formerror"';
   }
}

Posted: Sat Jan 20, 2007 7:06 pm
by feyd
"ez1234" passes the ereg() call. ;)