I have created a custom validation check for bootstrap form validator (it's the else part below):
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
else if (myConditionIsNotMet()) {
form.querySelector("#myInputField").classList.add('is-invalid');
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
The targeted input field already has a "required" attribute that works fine.
Using the above code, I have managed to make the validation error message appear and stop the form submission, but the outline of the field is green instead of red.
It seems my element ends up with both the is-valid and is-invalid classes due to the "required" validation.
I read in another post that there's an updateStatus function that can set a field as invalid. It seems that's what I need, but I haven't figured out how to access it via my form element.
Any help would be appreciated, I'm a noob when it comes to javascript:\
I'm pretty sure this is NOT the optimal solution, but I managed to get what I wanted with this:
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener('submit', function (event) {
if (myConditionIsNotMet()) {
form.querySelector("#myInputField").setCustomValidity("Oops!");
}
else {
form.querySelector("#myInputField").setCustomValidity("");
}
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.