I can't get my form to validate despite having the script both on the page and in my boilerplate layout. I have tried moving the tags around to different places but the server-side validation is the only part working.. the form won't run the client side validation.
<% layout('layouts/boilerplate') %>
<div class="row">
<h1 class="text-center">Create Artist Profile</h1>
<div class="col-6 offset-3">
<form action="/artists/new" method="POST" novalidate class="validated-form" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label" for="email">Email</label>
<input class="form-control" type="email" id="email" name="email" placeholder="name@domain.com" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="mb-3">
<label for="formFile" class="form-label">Upload band photo</label>
<input class="form-control" type="file" id="image" name="image" multiple="false">
</div>
<div class="mb-3">
<button class="btn btn-success">Create Profile</button>
</div>
<a href="/artists">All artists</a>
</form>
</div>
</div>
Here's the script tag from the body of my layouts/boilerplate.ejs
<script>
(function () {
'use strict'
bsCustomFileInput.init()
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.validated-form')
// Loop over them and prevent submission
Array.from(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
}, false)
})
})
</script>
Any ideas what I'm doing wrong with this form?
have you tried changing the form class to "needs-validation"?
also try this code
(function() {
'use strict';
window.addEventListener('load', function() {
var forms = document.querySelectorAll('.validated-form')
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);
})();