I need to execute some JavaScript if my form is valid. I am using Bootstrap 5 and found this code, but I am unsure how to add 'if form.is_valid {}'
<script>
(function () {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
if (form.valid(){ # but this not working } else { #this working }
// already tried using .valid , .is_valid, .isValid but no one work
form.classList.add('was-validated')
}, false)
})
})()
</script>
I also came across this snippet:
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec4dfdbcbdcd783d8cfc2c7cacfdac7c1c0ee9f809f97eef1f9e407">[email protected]</a>/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aab1b5a5b2b9edb6a1aca9a4a1b4a9afae80f1eef100f811">[email protected]</a>/dist/additional-methods.js"></script>
function validate_form2(form_id){
var form = $( "#" + String(form_id) );
form.validate();
$( "button" ).click(function() {
if (form.valid()){
loading_screen()
form.submit()
}
});
}
However, the issue with using that code is that the message 'Please fill out this field' appears inside the input field rather than as a tooltip.
Thank you!