优化JavaScript代码

时间:2016-04-29 19:08:36

标签: javascript regex validation

我已经编写了以下JS,它完成了工作,但是我在消除重复代码方面遇到了很多麻烦。我一直在破坏功能。

只是使用regex进行字段验证,如果输入与regex不匹配,则在相应字段下方添加错误消息。它是有效的,但我真的想开始编写更简洁的代码。

如果有人可以帮我这样做,我可以比较我的和你的,并开始了解如何处理这类任务。

感谢。

<form></form>

这是我的JSFiddle代码:https://jsfiddle.net/robinburrage/cnL2d4w8/2/

1 个答案:

答案 0 :(得分:0)

您可以对所有2次验证重复使用相同的功能。 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
相关问题