I've created a form with multiple input fields that are being validated using Bootstrap 5 validation.
<form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate>
[...]
</form>
As per the documentation, the code below is responsible for the validation:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(() => {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})()
Now I would like to trigger a JavaScript function upon successful form submission:
$('.asset-test').on('submit', function () {
alert('form submitted');
});
The issue is that this function executes even when some input fields do not pass the validation criteria set by Bootstrap.
I understand that every field needs to have the 'was-validated' class added. Do I need to check each individual input field? My knowledge of JavaScript is limited in this area. Could someone provide guidance on how to achieve this?
I'm looking to only run my JavaScript function if the Bootstrap validation is successful.