javascript 如何在 HTML 输入字段中阻止特殊字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46747287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:53:36  来源:igfitidea点击:

How to block special characters in HTML input field?

javascripthtmlnode.jsejs

提问by Sean Cortez

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

我只是想问一下如何在html输入字段中屏蔽<、>、"、/等特殊字符?

回答by Dror Moyal

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

您可以明确说明您接受哪些字符HTML 输入模式属性

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

回答by RaShe

Why not use html5?

为什么不使用 html5?

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

回答by selmansamet

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