Forum Moderators: coopster

Message Too Old, No Replies

numeric validation

         

trimast

1:44 pm on Aug 12, 2005 (gmt 0)

10+ Year Member



Hi All,

What is the best way to validation a form field that requires a numeric content only ie a telephone number or credit card number?

Something simple that will send an error message if the field contains anything except 0 to 9.

thanks

Rob

coopster

1:49 pm on Aug 12, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Hi trimast, and welcome to WebmasterWorld, btw.

I've found the best approach is a regular expression:

if (!preg_match('/[[:^digit:]]/', $_POST['number'])) { 
$error = 'You must enter numbers only.';
}

FiRe

2:09 pm on Aug 12, 2005 (gmt 0)

10+ Year Member



or use the actual PHP number check function - is_numeric() [php.net]

trimast

2:44 pm on Aug 12, 2005 (gmt 0)

10+ Year Member



Thanks both,

I tried both options earlier today but didn't have any luck, which is why i posted. I've just tried both options again, now knowing that i'm using the right function but still not having any luck.

The code i'm using is:

if (!preg_match('/[[:^digit:]]/', $_POST['t_tel'])) {
$error_tel = ERROR_MESSAGE;
}

but it seems to be allowing enteries with letters / no numbers through :( any ideas as to what i'm doing wrong? i've also tried:

if (!preg_match('/[[0-9]]/', $_POST['t_tel'])) {
$error_tel = ERROR_MESSAGE;
}

but still the same probs.

thanks

Rob

FiRe

2:59 pm on Aug 12, 2005 (gmt 0)

10+ Year Member



if (!is_numeric($_POST['t_tel'])) {
$error_tel = ERROR_MESSAGE;
}

trimast

3:24 pm on Aug 12, 2005 (gmt 0)

10+ Year Member



thanks, its working now, there was another problem with another part of the code as well as the numeric value, which was resulting in the numeric validation not working unless there was an error with another part of the form.

Its all working now though so thanks for the help!

Rob

jatar_k

3:30 pm on Aug 12, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



for type checking I much prefer the ctype functions [php.net] in this case ctype_digit