您可以重複使用相同的功能,爲所有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