-1

I have an input field that I validate @blur.

The goal is to allow 9 numbers grouped per 3 and a dot after, for example:

123456789 this should be masked to 123.456.789

But it should be possible too for the user to type 123.456.789 himself.

This is what I've got so far, I force the user to type 123.456.789

<input
    @blur="validateNumber($event.target.value)"
>


validateNumber(value) {
  if (/^(\d{3}\.){2}\d{3}$/.test(value)) {
     this.validNumber = true;
     return;
  } 

  this.validNumber = false;
  return;

}

I need a way to allow 123456789 and to make it 123.456.789

michael
  • 421
  • 6
  • 21

1 Answers1

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;
    }
  }
}
Cray
  • 2,774
  • 7
  • 22
  • 32
  • I don't think this will work, if they type 123456789 it needs to be masked as 123.456.789 and if they type 123.456.789 it should be okay. I miss here how to add the dots after a group of 3 characters – michael Jun 18 '20 at 07:23
  • I added a way you can mask it when the value is numeric – Cray Jun 18 '20 at 07:32