Vue JS - 如何限制输入字段中的特殊字符? [英] Vue JS - How to restrict special characters in an input field?
问题描述
在 Vue JS 中实现文本字符限制的最佳方法是什么?我希望使用 RegExp 来实现,这样用户就不会被允许在字段中输入符号.
我使用两管齐下的方法:
首先是将 watch
或 computed
值与 setter 一起使用,如 丹尼尔推荐以上.除了处理键盘输入外,它还可以通过拖放、粘贴或用户想出的任何其他方式处理输入.
第二个是 keydown
处理程序.仅使用监视值时,UI 会出现轻微延迟.受限字符在被移除前会短暂显示.为了获得更无缝的用户体验,keydown
侦听器会取消无效输入的键盘事件.
new Vue({el: "#app",数据: {姓名: "",},手表: {名称(val){this.name = val.replace(/\W/g, "");},},方法: {nameKeydown(e) {如果 (/^\W$/.test(e.key)) {e.preventDefault();}},},});
html {字体系列:无衬线;}.demo {显示:弹性;对齐内容:间隔;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><main id="应用程序"><p>尝试在每个框中键入空格、标点符号或特殊字符,以查看键处理程序产生的差异.</p><div class="demo"><div><div>没有键处理程序:</div><input type="text" v-model="name"/>
<div><div>带键处理程序:</div><input type="text" v-model="name" @keydown="nameKeydown($event)"/>
</main>
What's the best way to implement text-character restrictions in Vue JS ? I am looking to achieve with RegExp so that the user will not be allowed to type the symbols in the field.
I use a two pronged approach:
First is to use a watch
or computed
value with a setter, as Daniel recommends above. Besides handling keyboard input, it also handles input via drag and drop, paste, or whatever else the user comes up with.
Second is a keydown
handler. When using only a watched value, there is a slight delay in the UI. The restricted character is briefly displayed before being removed. For a more seamless user experience, the keydown
listener cancels the keyboard event for invalid input.
new Vue({
el: "#app",
data: {
name: "",
},
watch: {
name(val) {
this.name = val.replace(/\W/g, "");
},
},
methods: {
nameKeydown(e) {
if (/^\W$/.test(e.key)) {
e.preventDefault();
}
},
},
});
html {
font-family: sans-serif;
}
.demo {
display: flex;
justify-content: space-between;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<main id="app">
<p>Try typing spaces, punctuation, or special characters into each box to see the difference made by the key handler.</p>
<div class="demo">
<div>
<div>Without key handler:</div>
<input type="text" v-model="name" />
</div>
<div>
<div>With key handler:</div>
<input type="text" v-model="name" @keydown="nameKeydown($event)" />
</div>
</div>
</main>
这篇关于Vue JS - 如何限制输入字段中的特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!