あなたはすべて2つの検証のために同じ機能を再利用することができます
<form></form>
ここに私のJSFiddleコードです。 3つの機能の唯一の違いは、別の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この質問は、コードレビューではかなり話題になりません。 [トピックに関するヘルプセンター](http://codereview.stackexchange.com/help/on-topic)を読んで、CRを推薦するときは少し注意してください。 – Mast