我试图阻止输入写入和插入特殊字符。 这将阻止字符被写入,但不会阻止它们被插入。我怎样才能用 JQuery 做到这一点?
$('#first').keypress(function (e) {
var txt = String.fromCharCode(e.which);
if (!txt.match(/[A-Za-z0-9&. ]/)) {
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="form" action="reg.php" method="POST" id="reg" onsubmit="return formSubmit();">
<input type="text" name="first" id="first" required/>
<input type="text" name="sec" id="sec" required />
</form>
最佳答案
您可以使用下面的正则表达式来防止出现特殊字符
var nospecial=/^[^*|\":<>[\]{}`\\()';@&$]+$/;
$('#first').keypress(function (e) {
var txt = nospecial.test(e.val());
if (!txt) {
$('#first').val('');
return false;
}
});
关于javascript - 如何防止在输入字段中写入和粘贴特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911170/