2016-04-29 68 views
-2

我写了下面的JS,它完成了工作,但是我一直在解决重复代码时遇到了很多麻烦。我一直在打破功能。优化JavaScript代码

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

如果有人可以帮助我做到这一点,我可以比较我的和你的,并开始理解如何接近这种类型的任务。

谢谢。

<form></form> 

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

+0

请在这里发布您的代码。 –

+1

@ j08691在Code Review上,这个问题将会变得非常尖锐。请阅读我们的[主题帮助中心](http://codereview.stackexchange.com/help/on-topic),并在推荐CR时小心一点。 – Mast

回答

0

您可以重复使用相同的功能,为所有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 
+0

哦,不,我只注意到,尽管我正在测试一个似乎在debuggex.com中运行良好的正则表达式,但在我的代码(在上面的JSFiddle链接中),即使用户输入字母,错误消息也会消失。我知道隐藏和显示的错误信息完全与实际的验证片断分开,所以可能与另一个无关,但是谁能说出一些亮点? – user3472810