2016-04-29 71 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