0

My html is:

<input class="UserInfo" type="text" placeholder="phone Format" id="Phone_num">

Here is my js:

function checkPhoneFormat(){
const phone = document.getElementById("Phone_num").value;
const phoneFormatRex = /^\+?[0-9(),.-]+$/;
var match = phoneFormatRex.exec(phone);
if (match) {
    document.getElementById("Phone_num").value = phone;
}
else {
    document.getElementById("Phone_num").value = "";
}
}

what i want is to check the format of the phone after the user click outside the input field?

Ryan
  • 29
  • 1
  • 8

3 Answers3

3
document.getElementById("Phone_num").value

AND

document.getElementById("phone_num").value

There is a typo, Attribute values are always case-sensitive. The id value should either be Phone_num or phone_num

Sachin Yadav
  • 748
  • 9
  • 28
2

Is this what you are looking for?

    var input = document.getElementById("Phone_num");
    input.addEventListener("blur", function(){
        const phone = document.getElementById("Phone_num").value;
    const phoneFormatRex = /^\+?[0-9(),.-]+$/;
    var match = phoneFormatRex.exec(phone);
    if (match) {
        document.getElementById("Phone_num").value = phone;
    }
    else {
        document.getElementById("Phone_num").value = "";
    }
    })
<input class="UserInfo" type="text" placeholder="phone Format" id="Phone_num">
Aleksandar
  • 460
  • 3
  • 13
1

I believe what you are looking for is

<input type="text" onfocusout="myFunction()">

You can read more about it here W3 Schools onFocusOut

Calvin Bonner
  • 540
  • 2
  • 16
  • 1
    I guess this would just focus on the input field not check its type – Sachin Yadav Dec 01 '20 at 19:09
  • Sorry, I guess I should clarify. Using `onfocusout` with your function would cause it to run the `checkPhoneFormat()` function when focus is lost (e.g. when the user clicks off the input or tabs to the next input.) `onfocusout` does not make the input be in focus. – Calvin Bonner Dec 01 '20 at 19:11
  • yeah I've tried and it does not check the format of the value inside the input. So what can I do to make it check the format of the value of the input – Ryan Dec 01 '20 at 19:16
  • https://www.w3resource.com/javascript/form/phone-no-validation.php – Calvin Bonner Dec 01 '20 at 19:34