0

I want to validate an input box using javascript to prevent users from entering above a certain number. I have already done the validation for numbers. How do I prevent users from entering above a certain number? For example, users cannot enter more than 24.

I have tried onkeydown="return (this.value<25)"

HTML

<input type="text" size="2" maxlength="2" onkeydown="return ( event.ctrlKey || event.altKey
                || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
                || (95<event.keyCode && event.keyCode<106)
                || (event.keyCode==8) || (event.keyCode==9)
                || (event.keyCode>34 && event.keyCode<40)
                || (event.keyCode==46)
                || (parseInt(this.value, 10)<25))">
2
  • I don't think the input's value gets updated until after the key event, but in any case I wouldn't try to do it on keydown (or keyup or keypress), for two reasons: (1) It would be a bit weird from the user's point of view that the number keys higher than 2 only work some of the time, and it may take a while before they realise why; (2) Without using the keyboard the user can still paste in higher numbers (or letters). You should validate onsubmit of the form and/or onchange of the field. Commented Jul 29, 2011 at 3:15
  • hmm i think i will take your suggestion! Mods can close this question! Commented Jul 29, 2011 at 10:24

1 Answer 1

1

Be sure to use radix:

return (parseInt(this.value, 10)<25)
Sign up to request clarification or add additional context in comments.

1 Comment

I have tried this.. but it doesnt work, take a look at my updated question. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.