How to validate an input field in Vue3 using Regex?

3.8k Views Asked by At

How is it possible to have custom input field validation using Regex? I want input field to only have first 3 inputs as alphabets and last 3 inputs as numbers separated by "-". And I want to validate it same time use tries to type something.

I found only the solutions to validate numbers but when I try to use the same code for alphabets and number it does not work. Also I wanted the input field to validate for each key stroke.

<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>

This code works for the first input field but doesn't work for the second one. I might need to change something in mounted function where its trying to match the reg_regex but I am not getting an idea how to do it.

1

There are 1 best solutions below

0
On

Browsers support this natively using the pattern attribute:

<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"
  pattern="\w{3}-\d{3}"
/>

This will validate the form input client side as the user types.