Vue JS - 如何限制输入字段中的特殊字符?

vin*_*oth 7 vue.js vuejs2 vue-directives

在 Vue JS 中实现文本字符限制的最佳方法是什么?我希望使用 RegExp 来实现,这样用户就不会被允许在字段中输入符号。

gil*_*ly3 13

我使用两管齐下的方法:

首先是将 a watchorcomputed值与 setter一起使用,正如Daniel上面建议的那样。除了处理键盘输入外,它还可以通过拖放、粘贴或其他任何用户想出的方式处理输入。

其次是keydown处理程序。仅使用监视值时,UI 会出现轻微延迟。受限字符在被移除前会短暂显示。为了获得更无缝的用户体验,keydown侦听器会取消无效输入的键盘事件。

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();
      }
    },
  },
});
Run Code Online (Sandbox Code Playgroud)
html {
  font-family: sans-serif;
}

.demo {
  display: flex;
  justify-content: space-between;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 7

将 awatchcomputed值与 setter 和 getter 一起使用。

watch: {
  myAlphaNumField(newVal) {
    let re = /[^A-Z0-9]/gi;
    this.$set(this, 'myAlphaNumField', newVal.replace(re, ''));
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您希望正则表达式完全匹配模式,诀窍在于以允许所有字符直到最后一个的方式定义正则表达式。

例如,如果您想要正好有 5 位数字 ( #####),则正则表达式应该是\d{1,5}而不是\d{5},因为您需要能够在此之前键入前四位,但您仍将使用后面的一位来验证该字段是否已完成/完成/有效。

另一个例子,forA#A#A#将是[A-Z]([0-9]([A-Z]([0-9]([A-Z]([0-9])?)?)?)?)? 重点是,第一个之后的每个字符都是可选的,但前提是前面的字符可用

另一个例子###-AA\d(\d(\d(\-(\w(\w)?)?)?)?)?

您还可以使用现有的库,例如https://github.com/insin/inputmask-core(不包括 vue 扩展)或https://github.com/niksmr/vue-masked-input(其中做)

  • 不起作用:“[Vue warn]:避免在运行时向 Vue 实例或其根 $data 添加响应式属性 - 在 data 选项中预先声明它。” (2认同)