Just like the title I have an issue with the following code
function checkPhone(phone){
var reg = "/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im";
var result=phone.match(reg);
if (result) {
console.log("(true)phone "+phone);
return (true)
} else {
console.log("(error)phone "+phone);
}
}
<div class="form-group">
<label >Numero di Telefono</label><br>
<input type="text" id="phone" onchange="checkPhone(this.value)" placeholder="Insert phone number">
</div>
Regardless of what I try to put in phone, it will result in "(error)phone "+phone. I have also tried it online and it works.
How can I fix the issue?
The problem is that you have quotes around the regular expression. Try this:
function checkPhone(phone){
var reg = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
var result=phone.match(reg);
if (result) {
console.log("(true)phone "+phone);
return (true)
} else {
console.log("(error)phone "+phone);
}
}
<div class="form-group">
<label >Numero di Telefono</label><br>
<input type="text" id="phone" onchange="checkPhone(this.value)" placeholder="Insert phone number">
</div>