How to block special characters in HTML input fiel

2020-07-27 05:14发布

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

3条回答
家丑人穷心不美
2楼-- · 2020-07-27 05:39

Why not use html5?

<input type="text" pattern="[^()/><\][\\\x22,;|]+">
查看更多
虎瘦雄心在
3楼-- · 2020-07-27 05:48

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"/>

查看更多
We Are One
4楼-- · 2020-07-27 05:56

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">

查看更多
登录 后发表回答