How to block special characters in HTML input field? [closed]

爷,独闯天下 提交于 2019-12-08 11:45:07

问题


I just want ask if how I will block special characters such as <,>,",/,etc. in html input field?


回答1:


You can use regex.

document.getElementById("input").onkeypress = function(e) {
    /^[a-zA-Z0-9]+$/.test(this.value) // return true or false
};
<input type="text" id="input">



回答2:


You can explicitly state which characters you accept HTML input pattern Attribute

If you insist on blocking specific characters you can use the following:

document.getElementById("explicit-block-txt").onkeypress = function(e) {
    var chr = String.fromCharCode(e.which);
    if ("></\"".indexOf(chr) >= 0)
        return false;
};
<input type='text' id='explicit-block-txt' value='' onpaste="return false"/>



回答3:


Why not use html5?

<input type="text" pattern="[^()/><\][\\\x22,;|]+">


来源:https://stackoverflow.com/questions/46747287/how-to-block-special-characters-in-html-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!