0

I'm trying to do match a phone number with a regular expression:

this.Formareamedia.get('ladacontacto').valueChanges.subscribe((lada) => {
  let p;
  if (lada.length == 5) {
    p = '\\d{3}.\\d{4}';
  } else {
    p = '\\d{4}.\\d{4}';
  }
  this.Formareamedia.get("telefonocontacto").setValidators(Validators.pattern(new RegExp(p)));
  this.Formareamedia.get("telefonocontacto").updateValueAndValidity();
  this.ladacontacto = lada;
  let telefono = this.Formareamedia.get('telefonocontacto').value;
  console.log(new RegExp(p).lastIndex);
  if (telefono && telefono.match(new RegExp(p))) {
    return null;
  } else {
    return {
      telefono: false
    }
  }
});

If I put in the lada input (XX) and in the telefono input XXXX-XXXX the function is returning true (a correct result), but if I put in the lada input (XXX) and in the telefono input XXXX-XXXX is returning true a wrong result it is supposed to return false. What's wrong with my function?

chazsolo
  • 7,873
  • 1
  • 20
  • 44
David Medina
  • 39
  • 1
  • 3
  • 10

1 Answers1

0

You need to anchor your regex to the end of the string, like this:

 if (lada.length == 5) {
    p = '^\\d{3}.\\d{4}$';
  } else {
    p = '^\\d{4}.\\d{4}$';
  }

Otherwise it will match at least the number you specify (ignoring extra digits).

The same applies to the beginning of string: Specify '^'.

With '$' at the end it will ensure that the string ends with your digits.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57