Form validation is an essential part of any modern web application. It ensures that the data submitted by users is accurate, complete, and adheres to the specified rules. In this guide, we will explore how to implement form validation using Bootstrap 5, the latest version of the popular front-end framework.

Getting Started

To get started with Bootstrap 5 form validation, you need to include the necessary CSS and JavaScript files in your HTML document. You can either download the files and host them on your own server or use the CDN links provided by Bootstrap. Here is an example:


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/5.0.0-beta2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/5.0.0-beta2/js/bootstrap.bundle.min.js"></script>
    

Basic Form Structure

Next, you need to create the form structure using HTML markup. Bootstrap provides a set of CSS classes that you can use to style form elements and display validation feedback. Here is an example of a basic form:


<form class="needs-validation" novalidate>
    <div class="mb-3">
        <label for="name" class="form-label">Name</label>
        <input type="text" class="form-control" id="name" required>
        <div class="invalid-feedback">Please enter your name.</div>
    </div>
    
    <div class="mb-3">
        <label for="email" class="form-label">Email</label>
        <input type="email" class="form-control" id="email" required>
        <div class="invalid-feedback">Please enter a valid email address.</div>
    </div>
    
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
    

In the above example, the form element has the class needs-validation which is used to enable form validation. The novalidate attribute prevents the browser's default validation. Each form field has the class form-control for the styling and the required attribute to make the field mandatory. The invalid-feedback class is used to display the validation error messages.

Validating Form Fields

To validate the form fields, you need to add custom JavaScript code. Bootstrap 5 provides a set of utility classes and JavaScript methods to check the validity of the form fields and display error messages. Here is an example:


    (function () {
        'use strict';

        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.querySelectorAll('.needs-validation');

        // Loop over them and prevent submission
        Array.prototype.slice.call(forms)
           . forEach(function (form) {
                form.addEventListener('submit', function (event) {
                    if (!form.checkValidity()) {
                        event.preventDefault();
                        event.stopPropagation();
                    }

                    form.classList.add('was-validated');
                }, false);
            });
    })();
    

In the above code snippet, we first select all the forms with the class needs-validation. Then, we loop over each form and attach a submit event listener. Inside the event listener, we check if the form is valid using the checkValidity() method. If the form is invalid, we prevent the default form submission and stop the event propagation. Finally, we add the class was-validated to the form to apply the Bootstrap validation styles.

Conclusion

Bootstrap 5's form validation provides a convenient way to enhance the user experience and ensure data integrity in web applications. By following this guide, you can easily implement form validation using Bootstrap 5's built-in CSS and JavaScript features. Remember to always validate user input on the server-side as well to ensure maximum security.

Article by: Helpful Assistant