2016-06-11 25 views
0

我正在寫一個簡單的if語句來測試每個輸入框中的密碼是否匹配。如果它們都匹配,則不會給出錯誤,如果它們不匹配錯誤「它們不匹配」使用.setCustomValidity()給出。我遇到的問題是當給出錯誤,然後密碼更正匹配時,錯誤仍然給出。我不確定我做錯了什麼。下面是我的代碼和一個工作JSfiddle的鏈接。setCustomValidity問題

的jsfiddle:https://jsfiddle.net/1934foej/

HTML:

<label> 
    <input id="first" type="text" min="16" max="100" placeholder="New password" autofocus required> 
</label> 
<label> 
    <input id="second" type="text" min="16" max="100" placeholder="Repeat password" required> 
</label> 

<input id="submit" type="submit"> 

JS:

var firstPasswordInput = document.querySelector('#first'); 
var secondPasswordInput = document.querySelector('#second'); 
var submit = document.querySelector('#submit'); 


submit.onclick = function() { 
    var firstPassword = firstPasswordInput; 
    var secondPassword = secondPasswordInput; 

    //checks for match 
    if(firstPassword.value !== secondPassword.value) { 
     firstPasswordInput.setCustomValidity("they do not match"); 
     } 
} 
+0

@ImranAli運算符中沒有錯字,'!=='是一個有效的js等號運算符。 – ali404

回答

2

你正在做的錯誤是customValidity仍然"they do not match",因爲你沒有將其設置爲空字符串(瀏覽器將其視爲成功驗證),因此在驗證失敗後,輸入保持相同狀態。

submit.onclick = function() { 

    // there is no need to redefine these two variables 
    var firstPassword = firstPasswordInput; 
    var secondPassword = secondPasswordInput;  

    if(firstPassword.value !== secondPassword.value) { 
     firstPassword.setCustomValidity("they do not match"); 
    } 
    //add this part 
    else { 
     firstPassword.setCustomValidity(""); 
    } 

}