JavaScript 中的正则表达式,限制一些特殊字符,如"%,+,>,<,`"



我不想检查 not 条件。我只是希望正则表达式检查给定的字符并返回false如果有的话。

<form name="f" onsubmit="return onlyAlphabets()">
<input type="text" name="nm" onkeypress="return myFunction(event)">
<div id="notification"></div>
<input type="submit">
</form>
<script>
function myFunction(e) {
var regex = /^[%+<>]/g;
if (!regex.test(String.fromCharCode(e.keyCode))) {
return true;
} 
else {
<form name="f" onsubmit="return onlyAlphabets()">
<input type="text" name="nm" onkeypress="return myFunction(event)">
<div id="notification"></div>
<input type="submit">
</form>
<script>
function myFunction(e) {
var regex = /^[%+<>]/g   //   /^d+$/; // /^[a-zA-Zs]+$/;
if (!regex.test(String.fromCharCode(e.keyCode))) {
return true;
} 
else {         
return false;
}
}
</script>
<form name="f" onsubmit="return onlyAlphabets()">
<input type="text" name="nm" onkeypress="return myFunction(event)">
<div id="notification"></div>
<input type="submit">
</form>
<script>
function myFunction(e) {
var regex = /[^%+<>]/g;
if (!regex.test(String.fromCharCode(e.keyCode))) {
return true;
} 
else {         
return false;
}
}

尽管您尚未提供要禁用的内容的完整列表,因此这是更通用的目的

myFunction = e => /[*|":<>[]{}`\()';@%!&$]/.test(String.fromCharCode(e.keyCode))

最新更新