我试图阻止用户将不允许的文本粘贴到输入字段中。输入是随机生成的 8 位代码,包含字母和数字。
但我不希望用户粘贴任何包含其他字符的文本。
我的输入字段:
<input type='text' id='form-code-field' name='code' maxlength='8'>
注意:
我不是在寻找类似 readonly
属性的东西,因为用户仍然需要在字段中输入字母数字文本。
最佳答案
您可以在 input
事件上使用正则表达式来测试值输入:
$('#form-code-field').on('input', function(){
if(!/^[a-z0-9]+$/i.test(this.value)) this.value = $(this).data('oldValue') || "";
else $(this).data('oldValue', this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' id='form-code-field' name='code' maxlength='8'>
关于javascript - 防止未经允许的粘贴到文本输入中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33731827/