Javascript validation: Block special characters

后端 未结 7 1934
广开言路
广开言路 2020-12-09 05:50

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?

7条回答
  •  有刺的猬
    2020-12-09 06:46

    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.

提交回复
热议问题