Goal:
Phone number must be entered in this format, 208-111-1111; otherwise it shows the error message. What is the best way to show the error message when the user entered in the correct format but if the user re-entered in the correct format, the error message will disappear.
JS
phoneNumber = document.getElementById("phone");
var result = phoneNumber.toString().match(/^\d{3}-\d{3}-\d{4}$/);
function validatePhone(){
if (result == null)
{
error2.innerHTML = "The number is not in a correct format";
} else
{
error2.innerHTML = " ";
};
}
HTML
<p>Phone:</p>
<input type = "text" id="phone" name="phone" onChange="validatePhone()">
<br>
<span id="error2" ></span>
function validatePhone() { phoneNumber = document.getElementById("phone"); var result = phoneNumber.value.match(/^(\\d{3}-\\d{3}-\\d{4})?$/); if (result == null) { error2.innerHTML = "The number is not in a correct format"; } else { error2.innerHTML = " "; }; }
<p>Phone:</p> <input type="text" id="phone" name="phone" oninput="validatePhone()"> <br> <span id="error2"></span>
The problem is with the phoneNumber.toString()
call.
Calling toString()
on a DOM input element does not return the value of the user input. toString()
is intended to provide a string representation of the object it is called on, not retrieve a value held by the object.
phoneNumber.value
will return the value you are looking for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.