Page 1 of 1

Basic Form Validation of Integer Input

Posted: Sat Jan 22, 2011 3:36 pm
by Kray26
I'm having some trouble validating an entry to my form. When i enter a valid number such as 3285 i get the first error message ([7]) returned. I can't find anything wrong with my code so if anyone could point me in the right direction it would be appreciated. I have only been doing PHP for 2 weeks so it may be something simple for which i apologise.

Here is my code:

Code: Select all

if ($POST['extension'] != strval(intval($_POST['extension']))) {
		$errors[7] = 'Phone Extension must be a number';
		} else {
			if (($_POST['extension'] < 3000) || ($_POST['extension'] > 3599)) {
				$errors[8] = 'Extension must be between 3000 and 3599';
				}
		}
Here is my unexpected output:

Code: Select all


Phone Extension must be a number


Re: Basic Form Validation of Integer Input

Posted: Sat Jan 22, 2011 4:12 pm
by social_experiment
Form input is always string so you are passing a string value to intval, which returns 0 (or false). Try using is_numeric() to test if a value from a form is numeric.

Code: Select all

<?php
if (!is_numeric($_POST['extension'])) {
                $errors[7] = 'Phone Extension must be a number';
                } else {
                        if (($_POST['extension'] < 3000) || ($_POST['extension'] > 3599)) {
                                $errors[8] = 'Extension must be between 3000 and 3599';
                                }
                }
?>
Hth

Re: Basic Form Validation of Integer Input

Posted: Sat Jan 22, 2011 4:27 pm
by Kray26
Thank you social_experiment the is_numeric function works perfectly. Also thank you for the info about form input always being string this should help me out in the future.

Kray

Re: Basic Form Validation of Integer Input

Posted: Fri Feb 11, 2011 6:43 pm
by Technocrat
Just as an FYI ctypes are faster. In your case you ctype-digit

Re: Basic Form Validation of Integer Input

Posted: Sat Feb 12, 2011 9:06 pm
by Jonah Bron
If you don't want to validate it, and just want to force it clean, use intval(). Use instead of mysql_real_escape_string() for integers.

http://php.net/intval