0

我想验证输入字段,以便它只能采用大写字母和数字,并且我希望格式与 (AAA-111) 完全相同,这意味着前 3 个应该是字母,最后 3 个应该是数字,并且都用“-”分隔

<template>
  <div class="mt-6">
    <input
      type="text"
      placeholder="XXX-XXX"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number_plate"
    />
    <br />
  </div>
</template>
<script>
export default {
  props: ['template'],
  data: function() {
    return {
      number_plate: '',
      regex: '^[A-Z]{3}-d{3}'
    };
  },
  watch: {
    number_plate() {
      this.number_plate = this.number_plate.match(/(^[A-Z]{3})(\d{3})/g, '$1-$2');
    }
  }
};
</script>

我尝试使用这样的东西,但它不起作用,而且我对 Vue 也很陌生。

我遵循了一个教程,找到了以某种模式验证数字的解决方案,但是当我尝试修改它时,它不起作用。下面是代码片段,其中第一个输入字段工作正常,显示 000-000 中的数字,但第二个在我想要 AAA-000 之类的地方不起作用

<template>
  <div class="mt-6">
    <input
      type="text"
      :placeholder="number_template"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number"
    />
    <br /><br />
    <input
      type="text"
      :placeholder="reg_template"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number_plate"
    />
  </div>
</template>
<script>
export default {
  props: ['number_template', 'reg_template'],
  data: function() {
    return {
      number: '',
      number_format: '', // number pattern for now XXX-XXX
      regex: '', //regex for number pattern
      reg_regex: '', // regex for registration plate number
      reg_format: '', // pattern for registration number for now XXX-XXX (first 3 are letters and last 3 are numbers)
      number_plate: ''
    };
  },
  mounted() {
    let x = 1;
    this.format = this.number_template.replace(/X+/g, () => '$' + x++);
    console.log(this.format);
    this.number_template.match(/X+/g).forEach((char, key) => {
      this.regex += '(d{' + char.length + '})?';
      console.log(this.regex);
      console.log(char.length);
      console.log(key);
    });
    let y = 1;
    this.reg_format = this.reg_template.replace(/X+/g, () => '$' + y++);
    console.log(this.reg_format);
    this.reg_template.match(/X+/g).forEach((char, key) => {
      this.reg_regex += '(d{' + char.length + '})?';
      console.log(this.reg_regex);
      console.log(char.length);
      console.log(key);
    });
  },
  watch: {
    number() {
      this.number = this.number
        .replace(/[^0-9]/g, '')
        .replace(/^(\d{3})?(\d{3})/g, this.format)
        .substr(0, this.number_template.length);
    },
    number_plate() {
      this.number_plate = this.number_plate
        .replace(/([A-Z]{3})?(d{3})/g, this.format)
        .substr(0, this.reg_template.length);
    }
  }
};
</script>

4

1 回答 1

0

这与 Vue 无关。Html 已经可以为您做到这一点。但如果你想要一些自定义验证,那就另当别论了。在模板中尝试这个:

<input
      type="text"
      placeholder="XXX-XXX"
      pattern="^[A-Z]{3}-d{3}"
      class="w-56 text-2xl bg-grat-300 p-3 rounded-lg focus:outline-none"
      v-model="number_plate"
    />

除此之外,不知道从哪里来this.number

于 2021-05-17T07:40:32.880 回答