禁用'提交'除非检查框,否则按钮
从上一个问题开始,我问 提交按钮不使用JS验证
我真的很努力地在检查复选框的一部分以成为表单验证的一部分。
我的html是,
<h1>Applicant Form</h1>
<div class="container">
<form action="create-lead.php" id="newLead" class="form" method="POST">
<div class="form-field">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" id="firstName">
<small></small>
</div>
<div class="form-field ">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" id="lastName">
<small></small>
</div>
<div class="form-field">
<label for="email">Email</label>
<input type="text" name="email" id="email">
<small></small>
</div>
<div class="form-field">
<label for="telephone">Telephone</label>
<input type="text" name="telephone" id="telephone">
<small></small>
</div>
<div class="form-field dropdown">
<label for="buyerType" class="buyerType">Application Type</label>
<select class="secondary" 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 class="form-field">
<label class="check-container" for="accept">
<input class="check" type="checkbox" id="accept" name="accept" value="yes">
I agree to the <a href="#">terms and conditions</a>
</label>
<small></small>
</div>
<div class="form-field buttons">
<input class="submitButton" type="submit" name="submitButton" id="submitButton">
<input class="clear" 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()
和sumberbutton.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;
submitBtn.disabled = false;
} else {
// submitBtn.disabled == true;
submitBtn.disabled = true;
}
});
};
});
[2年后的编辑] 将比较运算符==
更改为=
在实现的解决方案中,请评论以表明我的愚蠢。
Following on from a previous question I asked
Submit button not working with JS validation
I have been really struggling with getting the checkbox being checked to be part of the form validation.
my html is
<h1>Applicant Form</h1>
<div class="container">
<form action="create-lead.php" id="newLead" class="form" method="POST">
<div class="form-field">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" id="firstName">
<small></small>
</div>
<div class="form-field ">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" id="lastName">
<small></small>
</div>
<div class="form-field">
<label for="email">Email</label>
<input type="text" name="email" id="email">
<small></small>
</div>
<div class="form-field">
<label for="telephone">Telephone</label>
<input type="text" name="telephone" id="telephone">
<small></small>
</div>
<div class="form-field dropdown">
<label for="buyerType" class="buyerType">Application Type</label>
<select class="secondary" 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 class="form-field">
<label class="check-container" for="accept">
<input class="check" type="checkbox" id="accept" name="accept" value="yes">
I agree to the <a href="#">terms and conditions</a>
</label>
<small></small>
</div>
<div class="form-field buttons">
<input class="submitButton" type="submit" name="submitButton" id="submitButton">
<input class="clear" type="reset" name="reset" id="reset">
</div>
</form>
</div>
<script src="js/app.js"></script>
and the app.js is
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;
}
}));
I have included the commented out section because that is the function I am working on to try and include the checkbox as part of the validation.
Everything else works perfectly, but I need to ensure the user accepts the terms and conditions before the form can be sent.
It seems that e.preventDefault()
and submitButton.disabled
aren't working as expected, unless I am missing something..
I am relatively new, and don't have the experience to get this working properly!
edit
On the advice of https://stackoverflow.com/a/72778291/18227124
I am rewriting the final validation to
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;
submitBtn.disabled = false;
} else {
// submitBtn.disabled == true;
submitBtn.disabled = true;
}
});
};
});
but again, I don't think I have implemented it correctly
[EDIT 2 Years later]
Changing comparison operator ==
to =
in the implemented solution, left it commented to show my foolishness.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码太长了,涉及检查,但是基本想法不是让用户单击提交按钮,直到他们通过了所有验证,而不是允许他们单击提交,然后查看所有内容是否有效。
因此,我们在复选框上设置
单击
事件处理程序,该复选框仅根据检查复选框而启用或禁用提交按钮。这样做时,不需要destextdefault()
。这是一个缩小的示例,您可以将其整合到代码中:
Your code is too long and involved to examine, but the basic idea is not to let the user click the submit button until they have passed all validations, rather than allow them to click submit and then see if everything is valid.
So we set up a
click
event handler on the checkbox that simply enables or disables the submit button based on whether the checkbox is checked. When done this way, there is no need forpreventDefault()
.Here's a scaled down example that you can incorporate into your code: