Bootstrap Form Validation
Bootstrap helps to show the result of the validation: green fields for valid and red fields for invalid values, with feedback messages. It uses the validation of the browser (HTML attributes like required), and adds a nice style.
Client side validation
Add novalidate and the class .needs-validation to the form. When the form is submitted, a small JavaScript checks it, and adds the class .was-validated. Then the fields show the valid or invalid style.
<form class="needs-validation" novalidate id="valForm">
<div class="mb-3">
<label for="vname" class="form-label">Name</label>
<input type="text" class="form-control" id="vname" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please write your name.</div>
</div>
<div class="mb-3">
<label for="vmail" class="form-label">Email</label>
<input type="email" class="form-control" id="vmail" required>
<div class="invalid-feedback">Please write a valid email.</div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" id="vagree" required>
<label class="form-check-label" for="vagree">I agree to the terms</label>
<div class="invalid-feedback">You must agree before you submit.</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<script>
document.querySelectorAll('.needs-validation').forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
</script>
Press Submit with empty fields in the preview. Let us test the same in real Chrome, first with an empty form and then with correct values:
const form = document.getElementById('valForm');
form.requestSubmit();
await new Promise(r => setTimeout(r, 200));
console.log('empty form: was-validated = ' + form.classList.contains('was-validated') + ', invalid fields = ' + form.querySelectorAll(':invalid').length);
document.getElementById('vname').value = 'Anita';
document.getElementById('vmail').value = 'anita@example.com';
document.getElementById('vagree').checked = true;
console.log('filled form: invalid fields = ' + form.querySelectorAll(':invalid').length + ', checkValidity() = ' + form.checkValidity());
empty form: was-validated = true, invalid fields = 3
filled form: invalid fields = 0, checkValidity() = true
The JavaScript explained
// find all the forms which need validation
const forms = document.querySelectorAll('.needs-validation');
forms.forEach(form => {
form.addEventListener('submit', event => {
// checkValidity() uses the HTML rules (required, type, pattern ...)
if (!form.checkValidity()) {
event.preventDefault(); // stop the sending
event.stopPropagation();
}
// show the green and red styles
form.classList.add('was-validated');
}, false);
});
Server side validation
When the server finds an error, send the page back with the classes .is-valid and .is-invalid already on the fields. You do not need the .was-validated class for this.
<div class="mb-3">
<label for="sv1" class="form-label">Username</label>
<input type="text" class="form-control is-invalid" id="sv1" value="anita">
<div class="invalid-feedback">This username is already taken.</div>
</div>
<div class="mb-3">
<label for="sv2" class="form-label">Email</label>
<input type="email" class="form-control is-valid" id="sv2" value="anita@example.com">
<div class="valid-feedback">Looks good!</div>
</div>
Important points
- Client side validation is for the comfort of the user. Always validate again on the server, because anybody can skip the JavaScript.
- Use the HTML attributes:
required,minlength,maxlength,pattern,min,maxand the righttype. .invalid-feedbackand.valid-feedbackare hidden until the field gets a state.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |