Hi,
How can I have people only enter NUMBERS not letters or other symbols in my php text box?
| SitePoint Sponsor |
Hi,
How can I have people only enter NUMBERS not letters or other symbols in my php text box?

I assume you mean 'within a form text box that will be submitted to a PHP script'.
The script that handles the form would have some logic to test for the data type that has been input for a specific variable, e.g. using the PHP function is_numeric() and related functions. You can also use a function like strlen() to verify the string is within a certain length (2 characters rather than 100 characters, for example).
Obviously this method only checks the value once the form was submitted; in order to make sure the user enters the correct data prior to the form submission, you want to use Javascript.


The best way is to use Regular Expressions: (They're not that scary!)
let's say the name of your form field is "total", should only be an integer (a whole number) and the form's method is a "post":
Receiving (form processing) script:
Of course you can expand upon that regular expression in the $regex variable, to check and dissallow characters and symbols and the like.PHP Code:$regex = "[a-z]|[A-Z]";
// If non-numeric characters are found, echo a warning message:
if(preg_match("#$regex#",$_POST['total']))
{
echo "No letter characters allowed!";
}
// Else allow the submit
else
{
// Do some other stuff like insert into database or have a cup of tea...
}
Check out the manual at:http://uk2.php.net/manual/en/ref.pcre.php
HTH![]()
- UK2NZ: mY bLoG
- Support Disclosure (and be amazed by it)
I'd disagree with phptek only because your question is pretty basic and simple in it needs. PHP has built in functions as bdl points out (is_numeric) that make it easier than worring about regular expressions when all you need is to check that the input is a number. Now if you need to do more advanced validation then regular expressions are invaluable and while they are complicated to look at for the newbie, once you've picked up some basics then they become friendlier.
Erh





I use is_numeric() most of the times for simple checking purposes.
A simple example would be...
PHP Code:if (!is_numeric($_POST['var'])) {
echo("Sorry only numbers are allowed");
exit;
}
Community Guidelines | Community FAQ
"He that is kind is free, though he is a slave;
he that is evil is a slave, though he be a king." - St. Augustine
If you want to check it in Javascript before you even submit your form (you can do this in addition to the PHP validation, but at the very least you should do the server-side validation), try this:Originally Posted by webmasts
You can pretty it up in a JS function too if you want.HTML Code:<input type="text" name="number" onblur="if (isNaN(this.value)) alert('Please enter only numbers in this field'); return false;">
Bookmarks