Page 1 of 1

Fixing Numeric Input

Posted: Fri Apr 27, 2007 3:27 pm
by timclaason
How do I deal with users entering a calculation in a text box?

For instance, I'm expecting users to enter a single number (ie 10) and they put a calculation in (2*5).
I want to prevent that from happening

Thanks in advance

Posted: Fri Apr 27, 2007 4:41 pm
by veridicus
Use the is_numeric() function. If it returns true for the value you can accept it.

Posted: Sat Apr 28, 2007 4:49 am
by Mohit_Prog
In the onChange event of a textbox, check value of the textbox with javascript. If a given value is not a number then put alert and take input again.

Posted: Sat Apr 28, 2007 5:18 am
by timvw
I think the conclusion is: Do not try to 'fix'.. Simply validate... and leave the fix to the user

Posted: Sat Apr 28, 2007 9:50 am
by Zu
veridicus wrote:Use the is_numeric() function. If it returns true for the value you can accept it.
Don't be so sure on that. is_numeric() is a very general function in testing for a number.

Posted: Sun Apr 29, 2007 5:31 am
by Ollie Saunders
You want to write an expression evaluator. In detail what do you want it to be capable of?
The basic principle of something like this is first to tokenize it and then to process the tokens. So "(1 + 3) * 5" becomes array(OpenParenthesis, Integer, OperatorPlus, CloseParenthesis, OperatorMultiply, Integer) you can then use various parsing techniques to perform the calculation, a recursive descendent parser might be of interest.

Posted: Sun Apr 29, 2007 10:03 am
by onion2k
Mohit_Prog wrote:In the onChange event of a textbox, check value of the textbox with javascript. If a given value is not a number then put alert and take input again.
If a user has JavaScript disabled then it won't work, so you have to check the value on the server anyway. Clientside validation is worthwhile because it improves the user's experience, but you should never rely on it for security or data integrity.

Posted: Sun Apr 29, 2007 10:05 am
by onion2k
ole wrote:The basic principle of something like this is first to tokenize it and then to process the tokens. So "(1 + 3) * 5" becomes array(OpenParenthesis, Integer, OperatorPlus, CloseParenthesis, OperatorMultiply, Integer) you can then use various parsing techniques to perform the calculation, a recursive descendent parser might be of interest.
You could just eval() it. :twisted:

(NOTE: This is a JOKE. Do NOT eval() incoming data.)

Posted: Sun Apr 29, 2007 10:34 am
by Ollie Saunders
You could just eval() it. :twisted:

(NOTE: This is a JOKE. Do NOT eval() incoming data.)
Yes, that occurred to me as well. Actually it is not completely impossible. You could tokenize it with token_get_all(), filter with a whitelist the legal tokens, rebuild it, eval. Probably pretty easy actually.