I have a simple form with bootstrap which I need to validate before submitting. It has auto support for invalid-feedback. It looks like this
let forms = document.querySelectorAll(".needs-validation");
var productNameField = document.getElementById("productName");
productNameField.addEventListener("input", function () {
var val = document.getElementById("productName").value;
console.log("not entering here if I don't enter an input", val);
if (!isValidString(val)) {
productNameField.setCustomValidity("invalid");
} else {
productNameField.setCustomValidity("");
}
});
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
console.log("not valid");
event.preventDefault();
event.stopPropagation();
}
console.log("here validation");
form.classList.add("was-validated");
},
false
);
});<form
action="/products/addProduct"
enctype="multipart/form-data"
class="needs-validation"
novalidate
method="post"
>
<div class="col-md-12 position-relative">
<label for="productName" class="form-label"
>Product Name</label
>
<input
type="text"
name="productName"
id="productName"
class="form-control"
/>
<div class="invalid-feedback">
Please provide a valid Product Name(at least two
characters, no special characters allowed).
</div>
</div>
<div>
<button type="submit" id="savebutton" name="Submit">
Create
</button>
</div>
</form>Now when I type an input I immediately see an error if !validString (because of the input eventlistener). But if I just click on the submit button it is not calling the validString function.
What should I do ?
Advertisement
Answer
const productNameField = document.getElementById("productName");
const isInputValid = function() {
return productNameField.value.length > 1;
}
const updateValidity = function() {
if (isInputValid()) {
productNameField.classList.remove('invalid')
} else {
productNameField.classList.add('invalid')
}
}
productNameField.addEventListener("input", updateValidity);
const forms = document.querySelectorAll(".needs-validation");
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
updateValidity();
if (isInputValid()) {
console.log("validation complete");
form.classList.add("was-validated");
} else {
console.log("validation failed");
event.preventDefault();
}
}
);
});