Javascript验证:阻止特殊字符 [英] Javascript validation: Block special characters
问题描述
如何限制用户在文本框中输入特殊字符。我只想输入数字和字母(输入/粘贴)。
How can I restrict users from entering special characters in the text box. I want only numbers and alphabets to be entered ( Typed / Pasted ).
任何样品?
推荐答案
你有两种方法:
- 检查按键事件。如果用户按下特殊字符键,请将其停在那里
- 检查onblur事件:当输入元素失去焦点时,验证其内容。如果该值无效,请在该输入框旁边显示谨慎的警告。
我建议使用第二种方法,因为它不那么刺激。还记得检查 onpaste
。如果你只使用按键那么我们可以复制并粘贴特殊字符,所以使用 onpaste
也限制粘贴特殊字符
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.
我认为这可能是为了防止SQL注入;如果是这样:你处理服务器端的检查更好。或者更好的是,转义值并将它们存储在数据库中。
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.
这篇关于Javascript验证:阻止特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!