繼上一個問題之后,我問 提交按鈕不適用于 JS 驗證
我一直在努力讓復選框被選中作為表單驗證的一部分。
我的 html 是
<h1>Applicant Form</h1>
<div >
<form action="create-lead.php" id="newLead" method="POST">
<div >
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" id="firstName">
<small></small>
</div>
<div >
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" id="lastName">
<small></small>
</div>
<div >
<label for="email">Email</label>
<input type="text" name="email" id="email">
<small></small>
</div>
<div >
<label for="telephone">Telephone</label>
<input type="text" name="telephone" id="telephone">
<small></small>
</div>
<div >
<label for="buyerType" >Application Type</label>
<select name="buyerType" id="buyerType">
<option value="Purchase">Purchase</option>
<option value="FirstTimeBuyer">First Time Buyer</option>
<option value="Remortgage">Remortgage</option>
<option value="RaiseFunds">Raise Funds</option>
</select>
</div>
<div >
<label for="accept">
<input type="checkbox" id="accept" name="accept" value="yes">
I agree to the <a href="#">terms and conditions</a>
</label>
<small></small>
</div>
<div >
<input type="submit" name="submitButton" id="submitButton">
<input type="reset" name="reset" id="reset">
</div>
</form>
</div>
<script src="js/app.js"></script>
app.js 是
const firstNameEl = document.querySelector('#firstName');
const lastNameEl = document.querySelector('#lastName');
const emailEl = document.querySelector('#email');
const telephoneEl = document.querySelector('#telephone');
const checkedEl = document.getElementById('#accept');
const submitButton = document.getElementById('#submitButton');
const form = document.querySelector('#newLead');
const checkFirstName = () => {
let valid = false;
const firstName = firstNameEl.value.trim();
if (!isRequired(firstName)) {
showError(firstNameEl, 'First name cannot be left blank');
} else if (!isFirstNameValid(firstName)) {
showError(firstNameEl, 'First name must only contain letters');
} else {
showSuccess(firstNameEl);
valid = true;
};
return valid;
};
const checkLastName = () => {
let valid = false;
const lastName = lastNameEl.value.trim();
if (!isRequired(lastName)) {
showError(lastNameEl, 'Last name cannot be left blank');
} else if (!isLastNameValid(lastName)) {
showError(lastNameEl, 'Last name must only contain letters');
} else {
showSuccess(lastNameEl);
valid = true;
}
return valid;
};
const checkEmail = () => {
let valid = false;
const email = emailEl.value.trim();
if (!isRequired(email)) {
showError(emailEl, 'Email field cannot be left blank');
} else if (!isEmailValid(email)) {
showError(emailEl, 'Email is not valid')
} else {
showSuccess(emailEl);
valid = true;
}
return valid;
};
const checkTelephone = () => {
let valid = false;
const telephone = telephoneEl.value.trim();
if (!isRequired(telephone)) {
showError(telephoneEl, 'Telephone field cannot be left blank');
} else if (!isTelephoneValid(telephone)) {
showError(telephoneEl, 'Number is not valid')
} else {
showSuccess(telephoneEl);
valid = true;
}
return valid;
};
// const checkedElValid = () => {
// if (!document.querySelector('#submitButton').checked) {
// showError(, 'You must accept the terms to continue')
// } else {
// showSuccess(accept);
// valid = true;
// }
// return valid;
// };
const isFirstNameValid = (firstName) => {
const re = /^[a-zA-Z] $/;
return re.test(firstName);
};
const isLastNameValid = (lastName) => {
const re = /^[a-zA-Z] $/;
return re.test(lastName);
};
const isEmailValid = (email) => {
const re = /^(([^<>()\[\]\\.,;:\s@"] (\.[^<>()\[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/;
return re.test(email);
};
const isTelephoneValid = (telephone) => {
const re = /^[0-9] $/;
return re.test(telephone);
};
const isRequired = value => value === '' ? false : true;
const showError = (input, message) => {
const formField = input.parentElement;
formField.classList.remove('success');
formField.classList.add('error');
const error = formField.querySelector('small');
error.textContent = message;
};
const showSuccess = (input) => {
const formField = input.parentElement;
formField.classList.remove('error');
formField.classList.add('success');
const error = formField.querySelector('small');
error.textContent = '';
}
form.addEventListener('submit', function(e) {
//validate fields
let isFirstNameValid = checkFirstName(),
isLastNameValid = checkLastName(),
isEmailValid = checkEmail(),
isTelephoneValid = checkTelephone();
IsCheckedElValid = checkedElValid();
let
isFormValid =
isFirstNameValid &&
isLastNameValid &&
isEmailValid &&
isTelephoneValid &&
IsCheckedElValid;
if (!isFormValid) {
e.preventDefault();
submitButton.disabled;
} else {
submitButton.disabled == false;
};
});
// real time validation
const debounce = (fn, delay = 500) => {
let timeoutId;
return (...args) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn.apply(null, args)
}, delay);
};
};
//event delegation
form.addEventListener('input', debounce(function(e) {
switch (e.target.id) {
case 'firstName':
checkFirstName();
break;
case 'lastName':
checkLastName();
break;
case 'email':
checkEmail();
break;
case 'telephone':
checkTelephone();
break;
}
}));
我已經包含了注釋掉的部分,因為這是我正在嘗試將復選框包含在驗證中的功能。
其他一切都完美無缺,但我需要確保用戶在發送表單之前接受條款和條件。
似乎e.preventDefault()并submitButton.disabled沒有按預期作業,除非我遺漏了什么..
我比較新,沒有經驗讓這個正常作業!
編輯
根據https://stackoverflow.com/a/72778291/18227124的建議
我正在將最終驗證重寫為
form.addEventListener("submit", function() {
//validate fields
let isFirstNameValid = checkFirstName(),
isLastNameValid = checkLastName(),
isEmailValid = checkEmail(),
isTelephoneValid = checkTelephone();
let
isFormValid =
isFirstNameValid &&
isLastNameValid &&
isEmailValid &&
isTelephoneValid;
if (isFormValid) {
let submitBtn = document.querySelector("button");
let checkBox = document.getElementById("accept");
checkBox.addEventListener("click", function () {
if (checkBox.checked) {
submitBtn.disabled == false;
} else {
submitBtn.disabled == true;
}
});
};
});
但同樣,我認為我沒有正確實施它
uj5u.com熱心網友回復:
您的代碼太長且難以檢查,但基本思想是在用戶通過所有驗證之前不要讓用戶單擊提交按鈕,而不是讓他們單擊提交然后查看一切是否有效。
所以我們在復選框上設定了一個click事件處理程式,它只是根據復選框是否被選中來啟用或禁用提交按鈕。以這種方式完成時,不需要preventDefault().
這是一個縮小的示例,您可以將其合并到您的代碼中:
let submitBtn = document.querySelector("button");
document.querySelector("input").addEventListener("click", function(){
if(this.checked){
submitBtn.disabled = false;
} else {
submitBtn.disabled = true;
}
});
<input type="checkbox"> I agree to the terms.
<button disabled>Submit</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/498204.html
標籤:javascript 形式 防止默认
上一篇:一個表格分布在多個頁面上
下一篇:使按鈕與另一個按鈕動態保持距離
