fbpx
Friday, December 8, 2023
Hire us on Freelancer.com for web development service
HomeLogin FormForm validation in bootstrap

Form validation in bootstrap

In today’s digital age, web forms play a crucial role in online interactions, from signing up for services to completing purchases. However, ensuring that the data submitted through these forms is accurate and reliable is of utmost importance. Bootstrap, a popular front-end framework, offers powerful form validation features to enhance the user experience and data integrity. In this article, we’ll explore the world of form validation in Bootstrap, guiding you through the essential concepts, techniques, and best practices.

Understanding Form Validation

Form validation is the process of confirming that the data entered by users in web forms meets predefined criteria or constraints. This ensures that the information is accurate and consistent, reducing errors and preventing invalid data from reaching the server. Bootstrap simplifies this process, providing built-in validation classes and JavaScript components to handle various validation scenarios.

Key Benefits of Form Validation in Bootstrap

Form validation in Bootstrap offers several advantages, enhancing both the user experience and data quality:

  • Improved User Experience: Validating data on the client-side allows users to receive instant feedback, reducing frustration and errors in real-time.
  • Enhanced Data Accuracy: Ensures that only valid data is submitted to the server, minimizing potential issues and data discrepancies.
  • Reduced Server Load: By eliminating invalid submissions early, server resources are conserved, leading to improved site performance.
  • Customization Options: Bootstrap provides a range of customizable validation styles, making it easy to adapt validation messages to your website’s design.
Getting Started with Bootstrap Form Validation

Before diving into the specifics of form validation, let’s cover the fundamental steps to set up a form using Bootstrap:

  • Include Bootstrap: Make sure you have Bootstrap properly included in your HTML document. You can either download it or use a Content Delivery Network (CDN).
  • HTML Structure: Create a form using HTML, ensuring you use Bootstrap’s predefined form elements and classes. For instance:
<form class="row g-3 needs-validation" novalidate>
                            
                            <div class="col-md-4">

                            	<label for="validationCustom01" class="form-label">First name</label>

                            	<input type="text" class="form-control" id="validationCustom01" value="Mark" required>
                            	
                            	<div class="valid-feedback">
                              		Looks good!
                            	</div>
                          	
                          	</div>
                            <div class="col-md-4">

                                <label for="validationCustom02" class="form-label">Last name</label>

                                <input type="text" class="form-control" id="validationCustom02" value="Otto" required>
                                <div class="valid-feedback">

                                  Looks good!

                                </div>

                            </div>

                            <div class="col-md-4">

                                <label for="validationCustomUsername" class="form-label">Username</label>

                                <div class="has-validation">
                                	
                                	
                                	<input type="text" class="form-control" id="validationCustomUsername" aria-describedby="inputGroupPrepend" required>
                                  		
                                  	<div class="invalid-feedback">
                                   		
                                   		Please choose a username.
                                  		
                                  	</div>

                                </div>

                            </div>

                          	<div class="col-md-6">

                            	<label for="validationCustom03" class="form-label">City</label>
                            	
                            	<input type="text" class="form-control" id="validationCustom03" required>
                                
                                <div class="invalid-feedback">
                                	
                                	Please provide a valid city.

                                </div>


                          	</div>
                            
                            <div class="col-md-3">

                                <label for="validationCustom04" class="form-label">State</label>

                                <select class="form-select" id="validationCustom04" required>
                                	
                                	<option selected disabled value="">Choose...</option>

                                  	<option>...</option>

                                </select>

                                <div class="invalid-feedback">

                                	Please select a valid state.

                                </div>

                            </div>

                          	<div class="col-md-3">

                            	<label for="validationCustom05" class="form-label">Zip</label>
                            	
                            	<input type="text" class="form-control" id="validationCustom05" required>
                            	
                            	<div class="invalid-feedback">

                              		Please provide a valid zip.
                            	
                            	</div>
                          	
                          	</div>

                            <div class="col-12">

                                <div class="form-check">
                                	
                                	<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
                                  	
                                  	<label class="form-check-label" for="invalidCheck">
                                    	
                                    	Agree to terms and conditions
                                  	
                                  	</label>
                                  	
                                  	<div class="invalid-feedback">
                                    	
                                    	You must agree before submitting.
                                  	
                                  	</div>

                                </div>

                            </div>

                            <div class="col-12 d-flex justify-content-center">

                                <button class="btn btn-primary w-75" type="submit">Submit form</button>
                            
                            </div>

                        </form>

Adding Validation Classes: Bootstrap provides classes for common validation scenarios. Add these classes to your form elements to enable validation:

  • required: Marks a field as mandatory.
  • valid-feedback: The message displayed when input is valid.
  • invalid-feedback: The message displayed when input is invalid.

JavaScript Integration: For client-side validation, you may need to include Bootstrap’s JavaScript components. For instance, if you want to validate a field as an email, add data-validation=”email” to the input element.

Common Validation Scenarios

Bootstrap simplifies handling various validation scenarios. Here are a few examples:

Required Fields
To make a field mandatory, add the required attribute to the input element:
<input type="text" class="form-control" id="username" placeholder="Enter username" required>
Email Validation

Bootstrap provides built-in support for email validation. Add the data-validation=”email” attribute to the input element:

<input type="email" class="form-control" id="email" placeholder="Enter email" data-validation="email">

Password Strength

You can check password strength by adding a data-validation attribute for a custom rule. For example, to enforce a strong password, you can use:

<input type="password" class="form-control" id="password" placeholder="Enter password" data-validation="custom" data-validation-regexp="^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$">

Custom Validation Messages

You can customize validation messages using valid-feedback and invalid-feedback classes:

<input type="text" class="form-control" id="customField" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please fill in this field.</div>

Number Ranges

For numerical input fields, you can use min and max attributes to define acceptable value ranges:

<input type="number" class="form-control" id="age" min="18" max="99">

 

Server-Side Validation

While client-side validation is essential for immediate feedback, server-side validation is equally crucial. It acts as a safety net to catch any potentially malicious or erroneous data that might bypass client-side checks. Always validate data on the server to ensure data integrity.

Combining Client-Side and Server-Side Validation

The ideal approach is to combine both client-side and server-side validation. Client-side validation enhances user experience, while server-side validation ensures data integrity and security. This two-tier validation approach offers a robust defense against invalid or malicious data.

Conclusion

Bootstrap provides a comprehensive solution for form validation, offering user-friendly feedback and data accuracy. By implementing client-side validation, you can enhance the user experience and reduce the likelihood of invalid data reaching your server. However, it’s crucial to remember that server-side validation is a non-negotiable aspect of web development to ensure data integrity and security.

To further expand your knowledge, consider exploring this article on creating a PHP Contact Us Form with jQuery AJAX. It covers advanced techniques for form handling and data submission, enhancing your web development skills.

Incorporating form validation in Bootstrap is not only about complying with web standards but also about enhancing the overall quality and user experience of your website. By understanding and implementing these techniques, you can create web forms that not only look good but also work seamlessly. So, go ahead, harness the power of Bootstrap, and keep your data accurate and your users happy.

Source Code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>Form validation in bootstrap</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

    <style type="text/css">

        *

        {
            margin: 0;
            padding: 0;
        }
        
        body

        {
            background-color: #6891EA;

        }

        .form-box

        {
            background: #fff;
            padding: 20px;
            border-radius: 10px;
        }

    </style>
</head>
<body>


    <div class="form-section mt-5">
        
        <div class="container">

            <h3 class="text-center fw-bold text-white mt-3 mb-5">Form validation in bootstrap</h3>
            
            <div class="row d-flex justify-content-center">
                
                <div class="col-lg-8 col-md-8 col-sm-12">
                    
                    <div class="form-box">
                        
                        <form class="row g-3 needs-validation" novalidate>
                            
                            <div class="col-md-4">

                            	<label for="validationCustom01" class="form-label">First name</label>

                            	<input type="text" class="form-control" id="validationCustom01" value="Mark" required>
                            	
                            	<div class="valid-feedback">
                              		Looks good!
                            	</div>
                          	
                          	</div>
                            <div class="col-md-4">

                                <label for="validationCustom02" class="form-label">Last name</label>

                                <input type="text" class="form-control" id="validationCustom02" value="Otto" required>
                                <div class="valid-feedback">

                                  Looks good!

                                </div>

                            </div>

                            <div class="col-md-4">

                                <label for="validationCustomUsername" class="form-label">Username</label>

                                <div class="has-validation">
                                	
                                	
                                	<input type="text" class="form-control" id="validationCustomUsername" aria-describedby="inputGroupPrepend" required>
                                  		
                                  	<div class="invalid-feedback">
                                   		
                                   		Please choose a username.
                                  		
                                  	</div>

                                </div>

                            </div>

                          	<div class="col-md-6">

                            	<label for="validationCustom03" class="form-label">City</label>
                            	
                            	<input type="text" class="form-control" id="validationCustom03" required>
                                
                                <div class="invalid-feedback">
                                	
                                	Please provide a valid city.

                                </div>


                          	</div>
                            
                            <div class="col-md-3">

                                <label for="validationCustom04" class="form-label">State</label>

                                <select class="form-select" id="validationCustom04" required>
                                	
                                	<option selected disabled value="">Choose...</option>

                                  	<option>...</option>

                                </select>

                                <div class="invalid-feedback">

                                	Please select a valid state.

                                </div>

                            </div>

                          	<div class="col-md-3">

                            	<label for="validationCustom05" class="form-label">Zip</label>
                            	
                            	<input type="text" class="form-control" id="validationCustom05" required>
                            	
                            	<div class="invalid-feedback">

                              		Please provide a valid zip.
                            	
                            	</div>
                          	
                          	</div>

                            <div class="col-12">

                                <div class="form-check">
                                	
                                	<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
                                  	
                                  	<label class="form-check-label" for="invalidCheck">
                                    	
                                    	Agree to terms and conditions
                                  	
                                  	</label>
                                  	
                                  	<div class="invalid-feedback">
                                    	
                                    	You must agree before submitting.
                                  	
                                  	</div>

                                </div>

                            </div>

                            <div class="col-12 d-flex justify-content-center">

                                <button class="btn btn-primary w-75" type="submit">Submit form</button>
                            
                            </div>

                        </form>

                    </div>

                </div>

            </div>

        </div>

    </div>



    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>


    <script type="text/javascript">
        
        // Example starter JavaScript for disabling form submissions if there are invalid fields
        (() => {
          'use strict'

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

          // Loop over them and prevent submission
          Array.from(forms).forEach(form => {
            form.addEventListener('submit', event => {
              if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
              }

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

    </script>

</body>
</html>
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Hire Us

Categories