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?