Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  178] [ 5]  / answers: 1 / hits: 149190  / 15 Years ago, mon, may 25, 2009, 12:00:00

How can I restrict users from entering special characters in the text box. I want only numbers and alphabets to be entered ( Typed / Pasted ).



Any samples?


More From » validation

 Answers
13

You have two approaches to this:




  1. check the keypress event. If the user presses a special character key, stop him right there

  2. check the onblur event: when the input element loses focus, validate its contents. If the value is invalid, display a discreet warning beside that input box.



I would suggest the second method because its less irritating. Remember to also check onpaste . If you use only keypress Then We Can Copy and paste special characters so use onpaste also to restrict Pasting special characters



Additionally, I will also suggest that you reconsider if you really want to prevent users from entering special characters. Because many people have $, #, @ and * in their passwords.



I presume that this might be in order to prevent SQL injection; if so: its better that you handle the checks server-side. Or better still, escape the values and store them in the database.


[#99464] Wednesday, May 20, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ibrahimr

Total Points: 468
Total Questions: 99
Total Answers: 93

Location: Serbia
Member since Sun, Jul 11, 2021
3 Years ago
;