I have a form (see it below). We follow bootstrap 4 on a project therefore I prefer to re-use as much as possible and do not write my own code where it is not needed.
When user press Submit button I do AJAX post request and as a response I get JSON object with some information. Based on that response I have to do some logic.
<form name="signin" class="js-form-submit needs-validation" action="/signin">
<div class="form-group">
<label for="username">User Name</label>
<input class="form-control" id="username" name="username" autofocus>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" >
</div>
<button type="submit" class="btn btn-primary mb-2">Submit/button>
</form>
Now I want to make client-side validation (and I prefer to use bootstrap if possible). They have an example but it works with normal submit but not with AJAX and I'm curious how can I perform bootstrap 4 client-side validation before my AJAX call?
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
https://getbootstrap.com/docs/4.0/components/forms/#custom-styles
Could somebody point me on a direction or maybe give a snippet of code.
Thanks.
I found a solution using JQuery. Try this code,
$('your-form-id').submit(function (event) {
event.preventDefault();
if ($('your-form-id')[0].checkValidity() === false) {
event.stopPropagation();
} else {
//do your ajax submition here
}
$('your-form-id').addClass('was-validated');
});
Add your ajax request to the else condition statement, this will do it.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}else {
//do your ajax submition here
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With