2016-08-02 78 views
2

我想爲我的密碼輸入設置第二個驗證消息,但它不起作用,您能幫我嗎?設置第二個驗證消息

這是我的標籤:

<input id="password" style="text-align:center;" type="text" name="password" 
     tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required 
     oninvalid="this.setCustomValidity('Please enter a password')" 
     oninput="this.setCustomValidity('')" 
     onkeyup="deleteBadConfirm(); valid_pass();" /> 

這也是畝js函數第二驗證消息:

function valid_pass() { 
    if(document.getElementById("password").value != "") { 
    document.getElementById("password") 
      .setCustomValidity('At least, enter 6 characters; Don't use any symbols'); 
    }; 
}; 

function deleteBadConfirm() { 
    $("#confirmpassword").prop("value", ""); 
}; 

編輯:這是它應該如何下去, 如果用戶在輸入密碼之前按提交,消息顯示「請輸入密碼」。然後,如果用戶輸入密碼,但它無效,這次該消息應該說「至少輸入6 ...」。現在,它顯示第一條消息,但是如果輸入少於6個字符,它仍會顯示舊消息,如果輸入6個無效字符,則不會顯示任何消息!

+0

「至少,輸入6個字符;不要使用任何符號' 是這個消息不顯示? –

+0

你能解釋一步一步的格式 –

+0

我剛剛編輯的問題,並解釋了我需要它的工作方式 –

回答

1

你有以下線路錯誤 通過添加一個轉義字符更改此

document.getElementById("password") 
      .setCustomValidity('At least, enter 6 characters; Don't use any symbols'); 

document.getElementById("password") 
      .setCustomValidity('At least, enter 6 characters; Don\'t use any symbols'); 

- 反斜槓()

+0

謝謝,但它仍然無效:( –

1

清除oninvalid事件或它總會覆蓋你的setCustomValidity。添加了:invalid CSS僞類來檢查值是否有效。

function valid_pass() { 
 
    if (document.getElementById("password").value != "") { 
 
    if ($('#password').is(":invalid")) { 
 
     document.getElementById("password") 
 
     .setCustomValidity('At least, enter 6 characters; Don\'t use any symbols'); 
 
    }; 
 
    } else { 
 
    document.getElementById("password") 
 
     .setCustomValidity('Please enter a password'); 
 
    }; 
 
}; 
 

 
function deleteBadConfirm() { 
 
    $("#confirmpassword").prop("value", ""); 
 
}; 
 

 
//Added this to show setCustomValidity message/tooltip without submit event 
 
function runReportValidity() { 
 
    document.getElementById("password").reportValidity(); 
 
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="password" style="text-align:center;" type="text" name="password" tabindex="3" pattern="[a-zA-Z0-9].{5,}" title="" required oninvalid="valid_pass()" oninput="this.setCustomValidity('')" onkeyup="deleteBadConfirm(); valid_pass();" /> 
 

 
<!-- Added this to show setCustomValidity message/tooltip without submit event --> 
 
<input type="button" onClick="runReportValidity()" value="Report Validity">

+0

這種有點奏效,但我仍然有一個問題:我只要給定的密碼無效;我甚至在我原來的代碼中有if語句: 'if(document.getElementById(「password」)。invalid){document.getElementById(「password」 ).setCustomValidity('至少輸入6 ...');} else {document.getElementById(「password」)。setCustomValidity('');};' –

+0

@TheMonster現在更新我的答案我見過你編輯。 – Cobote