Validate a required field with Bootstrap
Description: Create a form with a required name field. When the user submits it empty, the field must be red with the message “Please write your name”.
Hint:
- Use
novalidate,.needs-validation,.invalid-feedback,checkValidity()and the classwas-validated.
Solution
<form class="needs-validation" novalidate id="f">
<label for="vn" class="form-label">Name</label>
<input type="text" class="form-control" id="vn" required>
<div class="invalid-feedback">Please write your name.</div>
<button class="btn btn-primary mt-3" type="submit">Submit</button>
</form>
<script>
document.getElementById('f').addEventListener('submit', function (e) {
if (!this.checkValidity()) { e.preventDefault(); e.stopPropagation(); }
this.classList.add('was-validated');
});
</script>
Live preview
const f = document.getElementById('f');
f.requestSubmit();
await new Promise(r => setTimeout(r, 200));
console.log('was-validated class: ' + f.classList.contains('was-validated'));
console.log('field is invalid: ' + !document.getElementById('vn').checkValidity());
console.log('message color: ' + getComputedStyle(document.querySelector('.invalid-feedback')).color + ', display: ' + getComputedStyle(document.querySelector('.invalid-feedback')).display);
Console output (real Chrome)
was-validated class: true
field is invalid: true
message color: rgb(220, 53, 69), display: block
How it works
- The browser checks the
requiredattribute withcheckValidity(). - After
was-validatedis added, Bootstrap shows the red border and the.invalid-feedbacktext.
Read Form Validation.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |