在簡單的HTML表單上練習我的Javascript。在一個框中輸入密碼,再次輸入確認。密碼應該包含6個字符(包括1個數字),並且沒有空格。如果密碼符合條件並匹配,則應彈出警告消息。Javascript表單驗證不成功
我主要在那裏,如果條件不符合,彈出錯誤消息,但我無法提醒「成功!」。我用if語句玩弄了很多方法,我不確定我錯過了什麼。有什麼建議麼?
的Javascript:
window.onload = function() {
document.getElementById('submit').addEventListener('click', validateInput);
}
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
function validatePassword() {
var userPass = document.getElementById('password').value;
if (userPass.length == 0) { // Nothing was entered
document.getElementById('password_error').innerHTML = 'Please enter a password';
} else if (userPass.length < 6) { // Less than 6 chars
document.getElementById('password_error').innerHTML = 'Your password must be at least 6 characters in length';
} else if (userPass.match(/\s/)) { // contains a space
document.getElementById('password_error').innerHTML = 'Your password cannot contain spaces';
} else if (!userPass.match(/\d/)) { // Does not contain a number
document.getElementById('password_error').innerHTML = 'Your password must contain a number';
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateConfirm() {
function clearFields(){
document.getElementById('password').value=null;
document.getElementById('confirm_password').value=null;
}
if (confirmPass.length == 0) {
document.getElementById('confirm_error').innerHTML = "Please confirm password to proceed";
} else if (confirmPass.length < 6) {
document.getElementById('confirm_error').innerHTML = "Your password must be at least 6 characters in length";
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateInput() {
validatePassword();
validateConfirm();
}
形式:
<form>
<fieldset>
<legend>CONFIRM PASSWORD</legend>
<label for="name">Password: </label>
<input type="text" id="password" size="10" />
<p id="password_error" class="error"></p>
<label for="name">Confirm Password: </label>
<input type="text" id="confirm_password" size="10" />
<p id="confirm_error" class="error"></p>
<button id="submit">Submit</button>
</fieldset>
</form>
有validatePassword'的'範圍內沒有clearFields,所以這應該是一個問題 –