您可以重复使用相同的功能,为所有2个验证。这三个功能之间的唯一区别是,您试图追加到不同的id
。
使用this
而不是专指元素,因为输入无论如何绑定到您正在寻找的元素。
phone.addEventListener('keyup', validatePhone);
phone2.addEventListener('keyup', validatePhone);
phone3.addEventListener('keyup', validatePhone);
function validatePhone(evt) {
var pattern = /^(\(\d{1,2}\)\s)?\(?\d{4}\-\)?[\s.-]?\d{4}$/; //set the regular expression
var str = this.value; //get the user's input
var phoneVal = document.getElementById("phoneVal");
if (phoneVal) { //if the error message div is already on the page
phoneVal.parentNode.removeChild(phoneVal); //remove it, to prevent a series of error message divs from accumulating
}
if (str === "") {//if there is no user input
phoneVal.parentNode.removeChild(phoneVal);//remove the error message
}
if (pattern.test(str) === false) { //if the string doesn't match the expression
var elem = document.createElement("div"); //create a DIV
elem.setAttribute("id", "phoneVal"); //give it an 1)id, 2)class and 3)message
elem.setAttribute("class", "form-error-msg");
if(window.location.href.indexOf("/en") > -1) {
elem.innerHTML = 'Please enter a valid telephone number.';
}else{
elem.innerHTML = 'Por favor introduce un número de teléfono válido.';
}
this.parentNode.appendChild(elem); //add the div with the current error message
}
} //end function
请在这里发布您的代码。 –
@ j08691在Code Review上,这个问题将会变得非常尖锐。请阅读我们的[主题帮助中心](http://codereview.stackexchange.com/help/on-topic),并在推荐CR时小心一点。 – Mast