Javascript validation: Block special characters

后端 未结 7 1935
广开言路
广开言路 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:41

    I think checking keypress events is not completely adequate, as I believe users can copy/paste into input boxes without triggering a keypress.

    So onblur is probably somewhat more reliable (but is less immediate).

    To truly make sure characters you don't want are not entered into input boxes (or textareas, etc.), I think you will need to

    1. check keypress (if you want to give immediate feedback) and
    2. also check onblur,
    3. as well as validating inputs on the server (which is the only real way to make sure nothing unwanted gets into your data).

    The code samples in the other answers will work fine for doing the client-side checks (just don't rely only on checking keypress events), but as was pointed out in the accepted answer, a server-side check is really required.

提交回复
热议问题