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
JavaScript
x
29
29
1
let forms = document.querySelectorAll(".needs-validation");
2
var productNameField = document.getElementById("productName");
3
4
productNameField.addEventListener("input", function () {
5
var val = document.getElementById("productName").value;
6
console.log("not entering here if I don't enter an input", val);
7
if (!isValidString(val)) {
8
productNameField.setCustomValidity("invalid");
9
} else {
10
productNameField.setCustomValidity("");
11
}
12
});
13
14
15
Array.prototype.slice.call(forms).forEach(function (form) {
16
form.addEventListener(
17
"submit",
18
function (event) {
19
if (!form.checkValidity()) {
20
console.log("not valid");
21
event.preventDefault();
22
event.stopPropagation();
23
}
24
console.log("here validation");
25
form.classList.add("was-validated");
26
},
27
false
28
);
29
});
JavaScript
1
29
29
1
<form
2
action="/products/addProduct"
3
enctype="multipart/form-data"
4
class="needs-validation"
5
novalidate
6
method="post"
7
>
8
<div class="col-md-12 position-relative">
9
<label for="productName" class="form-label"
10
>Product Name</label
11
>
12
<input
13
type="text"
14
name="productName"
15
id="productName"
16
class="form-control"
17
/>
18
<div class="invalid-feedback">
19
Please provide a valid Product Name(at least two
20
characters, no special characters allowed).
21
</div>
22
</div>
23
24
<div>
25
<button type="submit" id="savebutton" name="Submit">
26
Create
27
</button>
28
</div>
29
</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
JavaScript
1
34
34
1
const productNameField = document.getElementById("productName");
2
3
const isInputValid = function() {
4
return productNameField.value.length > 1;
5
}
6
const updateValidity = function() {
7
if (isInputValid()) {
8
productNameField.classList.remove('invalid')
9
} else {
10
productNameField.classList.add('invalid')
11
}
12
}
13
14
productNameField.addEventListener("input", updateValidity);
15
16
17
const forms = document.querySelectorAll(".needs-validation");
18
19
Array.prototype.slice.call(forms).forEach(function (form) {
20
form.addEventListener(
21
"submit",
22
function (event) {
23
updateValidity();
24
if (isInputValid()) {
25
console.log("validation complete");
26
form.classList.add("was-validated");
27
} else {
28
console.log("validation failed");
29
event.preventDefault();
30
}
31
}
32
);
33
});
34