By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,996 Members | 884 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,996 IT Pros & Developers. It's quick & easy.

Validate User Input

P: 8
Hey all!

I am making a very simple program which requires the user to enter a numerical value into a text box (html form) and then multiplies it by 10 before echoing back. The program is working fine.

However, when I enter some letters, php returns an ugly error. Is there a way to prevent the user from entering letters?

Dec 22 '07 #1
Share this Question
Share on Google+
1 Reply

Expert 5K+
P: 6,050
This was a little learning curve for me. So thanks for letting me help you :D!

I'll start with the code:

$stringGood = "2345634545156456";
$stringBad = "32873428473t30984";

$pattern = '/[^0-9]/'; //pattern for regular expression
if(preg_match($pattern, $stringBad)){
echo "String: $stringBad, contained characters <em>other than</em> numbers.";
} else {
echo "String was good.";

echo "<br /><br />

if(preg_match($pattern, $stringGood)){
echo "String: <strong>$stringGood</strong>, contained characters <em>other than</em> numbers.";
} else {
echo "String was good.";

You better read this!
First we start off with the strings we are going to check ($stringGood, $stringBad) named like so for obvious reasons ;) - i assume you'll need to change the variables to something like:
$string = $_POST['number'];
The next thing ($patter) is the pattern we will use for the regular expression, and don't be worried if these scare you - they scare me! But once you try it for yourself they aren't too ghastly.
Basically what the pattern is saying is:
[start pattern ^check for something that is NOT 0-9included in this part ]end pattern.
So we're checking for anything that is not within the scope of 0, 1, 2...
Easy eh?
Next we're onto the preg_match. What this does is check the given subject for any given regular expression. Great. Exactly what we need.
If the given expression is found in the given subject; it will return 1 / true. And i bet you can tell me what it returns if it isn't found? ;)
So so:
if(preg_match returns TRUE){
//pattern was found - execute code.
} else {
//pattern not found - execute code.

Hope this long winded solution helps!

Any questions just post back :)

Dec 22 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.