Vuetify 字符串数字组合的验证规则

Vuetify validation rules for string numeric combination

我正在尝试确定如何使用 Vuetify 验证来确保规则(在 v-text-field 上使用 :rules 标签)符合这种格式:

AB-12345678(前两个字符是字母,后跟连字符,然后是 8 位数字)

我在不使用 CharAt 的情况下努力做到这一点,但我认为有一种更干净、更简单的方法。

您应该考虑使用正则表达式。类似于:^[A-Z]{2}-[0-9]{8}$ 应该有效。

要在 javascript 中使用正则表达式,您应该参考 Mozilla developers docs

看起来像这样:

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found);
// expected output: Array ["T", "I"]

您可以使用正则表达式来检查可用性

正则表达式规则:[A-B]{2}-[0-9]{8}

检查代码

<template>   
  <v-text-field
      :rules="customRule"
  />
</template>

<script>

export default {
  computed: {
    customRule() {
      return [
        v => /[A-B]{2}\-[0-9]{8}/.test(v) || "rule is not valid"
      ],
    }
  }
}

</script>

我会使用正则表达式

<v-text-field
  :rules="[v => /^[A-Z]{2}-\d{8}$/gm.test(v)]"
/>

这完全取决于你想要什么,但这个正则表达式正在做:

  • ^ 匹配行首
  • [A-Z]{2} 正好匹配2个大写字符
    • 如果 upper/lowercase 无关紧要,请使用 [A-Za-z]{2}
  • - 匹配破折号
  • \d{8}匹配8位数字
  • $ 匹配行尾
  • gm 最后是正则表达式的标志

Here's a page to test it