[Vuejs]-Vue validate input with regex add mask

2👍

You can use OR operator | to add the numeric-only check to your existing pattern

(^\d{9}$)|(^(\d{3}\.){2}\d{3}$)

Or make it more readable with two separate checks

if (/^\d{9}$/.test(value) || /^(\d{3}\.){2}\d{3}$/.test(value))

To add the mask separate the checks and modify the value if it is numeric, something like:

<input v-model="number" @blur="validateNumber">

data() {
  return {
    valid: false,
    number: "",
  };
},
methods: {
  validateNumber() {
    if (/^\d{9}$/.test(this.number)) {
      this.number = this.number.replace(/(\d{3})(\d{3})(\d{3})/, "$1.$2.$3");
      this.valid = true;
    } else if (/^(\d{3}\.){2}\d{3}$/.test(this.number)) {
      this.valid = true;
    } else {
      this.valid = false;
    }
  }
}

Leave a comment