Fixing Numeric Input
Moderator: General Moderators
-
timclaason
- Forum Commoner
- Posts: 77
- Joined: Tue Dec 16, 2003 9:06 am
- Location: WI
Fixing Numeric Input
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
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
-
Mohit_Prog
- Forum Commoner
- Posts: 26
- Joined: Mon Apr 23, 2007 6:10 am
- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
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.
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.
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.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.
You could just eval() it.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.
(NOTE: This is a JOKE. Do NOT eval() incoming data.)
- Ollie Saunders
- DevNet Master
- Posts: 3179
- Joined: Tue May 24, 2005 6:01 pm
- Location: UK
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.You could just eval() it.![]()
(NOTE: This is a JOKE. Do NOT eval() incoming data.)