PDA

View Full Version : Make a Text field only accept ints?


-fedexer-
12-02-2007, 06:43 PM
Hello , i have just started using PHP and i have everythign working fine, but i would like to make one of the text fields that is gathering data to only accept integers.... i have tried all different things from the PHP site, but i just seem to get no-where. I was wondering if someone could explain what function i should be using.


Thanks
-fedexer-

davidj
12-02-2007, 07:58 PM
do you want to evaluate the data before the submit or at the server

-fedexer-
12-03-2007, 05:59 AM
Before the submit, i think this would be best.

Thanks
-fedexer-

davidj
12-03-2007, 06:09 AM
well you could do both as you want to be sure that only numerics are keyed so for those people who defeat javascript you catch them at the server

ok

javascript function...


function checkfield(){

f1 = document.getElementById('field1').value; //<< this is the field that only accepts ints

if(! isNaN(f1)){

document.getElementById('form1').submit();

}else{

alert("one of your fields has invalid data");

}


}


turn the submit button into a button and fire the function onclick="checkfield()"

-fedexer-
12-03-2007, 06:17 AM
Thanks david, ill go give that a try ;) ill report back

Edit: What would the server side code be also?

-fedexer-
12-03-2007, 06:49 AM
Ill check back here later for your reply, my server aint working currently so i cant test it yet, and now ive got to go to work experience, woah how fun. Didn't think i would be working in a big company at 15 8-)

Thanks for the help so far david

-fedexer-

lux
12-03-2007, 09:59 AM
to check the value sever side you can use the is_int($foo) function

where $foo is the variable value submitted in the form.


$foo = $_POST['int_field'];

if(is_int($foo)){
//value submitted is int.
}else{
//value submitted is NOT an int.
}


also look up is_numeric() on php.net, very helpful function as well