Open In App

Bootstrap5 Validation SASS

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Bootstrap 5 introduced a new feature to form validation using SASS, which is a powerful CSS preprocessor. SASS allows developers to write more maintainable and organized code by providing features like variables, mixins, maps, and loops. By leveraging these features, users can easily customize the validation styles and behavior according to their project requirements and also gets the advantage of code reusability.

Bootstrap5 Validation SASS variables

Bootstrap5 Validation SASS variables are the following:

$form-feedback-margin-top: $form-text-margin-top;
$form-feedback-font-size: $form-text-font-size;
$form-feedback-font-style: $form-text-font-style;
$form-feedback-valid-color: $success;
$form-feedback-invalid-color: $danger;
$form-feedback-icon-valid-color: $form-feedback-valid-color;
$form-feedback-icon-valid: url("data:image/svg+xml,<svg /*svg properties*//></svg>");
$form-feedback-icon-invalid-color: $form-feedback-invalid-color;
$form-feedback-icon-invalid: url("data:image/svg+xml,<svg /*svg properties*/></svg>");

Steps to override scss of Bootstrap

Step 1: Install Bootstrap using the following command:

npm i bootstrap

Step 2: Create your custom scss file and write the variable you want to override. Then include the bootstrap scss file using import.

$class_to_override: values;
@import "node_modules/bootstrap/scss/bootstrap"

Step 3: Convert the file to CSS using live server extension.

Step 4: Include the converted scss file to your HTML after the link tag of Bootstrap css

Bootstrap 5 Validation SASS

  • Variables: Sass variables are used to store reusable values, such as colors, fonts, or dimensions. Variables can be used to customize the colors, borders, and other visual aspects of validation messages and form controls.
  • Mixins: Mixins are reusable blocks of CSS code that can be included in other styles. In Bootstrap 5 validation, mixins can be utilized to define and apply common styles for validation states like success, error, and warning.
  • Maps: Sass maps are key-value pairs that allow you to store and access data. In Bootstrap 5 validation, maps can be employed to define validation styles for different form control types or to create custom validation classes.
  • Loops: Loops in Sass enable you to iterate over a set of values and perform actions repetitively. When it comes to Bootstrap 5 validation, loops can be used to generate styles for different validation states or to apply styles to multiple form controls simultaneously.
  • Customizing: Bootstrap 5 validation Sass provides extensive customization options to tailor the validation styles and behavior to your liking. Users can override the default Sass variables, mixins, maps, and loop configurations to achieve a unique look and feel for your forms.

Example 1: In this example, we have a  contact form with input fields for name, email, and message. The form utilizes Bootstrap 5 validation classes (is-valid and is-invalid) for styling and feedback messages. The SASS code contains mixins that override the Bootstrap mixins to customize the validation styles.

HTML




<!DOCTYPE html>
<html lang="en">
   
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge" />
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0" />
    <title>Bootstrap5 Validation Sass</title>
    <link rel="stylesheet"
          href="./custom.css" />
</head>
<body>
    <form class="was-validated">
        <h1 style="color: rgb(11, 156, 11)">
            GeeksforGeeks
        </h1>
        <div class="mb-3">
            <label for="nameInput"
                   class="form-label">
                Name
              </label>
            <input
                   type="text"
                   class="form-control"
                   id="nameInput" required />
            <div class="invalid-feedback">
                Please enter your name.
            </div>
        </div>
        <div class="mb-3">
            <label
                   for="emailInput"
                   class="form-label">
                Email
            </label>
            <input type="email"
                   class="form-control"
                   id="emailInput" required />
            <div class="invalid-feedback">
                Please enter a valid email address.
            </div>
        </div>
        <div class="mb-3">
            <label
                   for="messageInput"
                   class="form-label">
                Message
            </label>
            <textarea
                      class="form-control"
                      id="messageInput" required>
              </textarea>
            <div class="valid-feedback">
                Message received. We'll get back to you
                soon!
            </div>
        </div>
        <button type="submit" class="btn btn-primary">
            Send
        </button>
    </form>
 
    <script>
        // Get the form element
        const form = document.querySelector(
            ".was-validated"
        );
 
        // Add an event listener for the form's submit event
        form.addEventListener(
            "submit",
            function (event) {
                // Check if the form is valid
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
 
                // Add or remove the validation classes
                // based on the input's validity state
                Array.from(form.elements).forEach(
                    function (input) {
                        if (input.checkValidity()) {
                            input.classList.remove(
                                "is-invalid"
                            );
                            input.classList.add(
                                "is-valid"
                            );
                        } else {
                            input.classList.remove(
                                "is-valid"
                            );
                            input.classList.add(
                                "is-invalid"
                            );
                        }
                    }
                );
 
                // Mark the form as validated
                form.classList.add("was-validated");
            }
        );
    </script>
</body>
 
</html>


CSS




// custom.scss
 
// Import Bootstrap
@import "./node_modules/bootstrap/scss/bootstrap";
 
// Override Bootstrap mixins
@mixin form-validation-icons() {
    .is-valid {
        &::after {
            @include svg-icon(
                "check-circle-fill",
                $size: 1em,
                $color: #00ff00
            );
        }
    }
 
    .is-invalid {
        &::after {
            @include svg-icon(
                "exclamation-triangle-fill",
                $size: 1em,
                $color: #ff0000
            );
        }
    }
}


CSS




/* custom.css */
form {
    display: flex;
    flex-direction: column;
    align-items: center;
    max-width: 400px;
    margin: 0 auto;
}


Output:

contact-form-validation_gfg

Working Bootstrap 5 validation using SASS

Example 2: In this example, we have created a user registration form with valid-feedback and invalid-feedback functionalities where at first feedback is provided to the user for invalid input and when a valid input is provided by the user another feedback appears in green color ensuring the validation of the input using SASS.

HTML




<!DOCTYPE html>
<html lang="en">
   
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge" />
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0" />
    <title>Bootstrap5 Validation Sass</title>
    <link rel="stylesheet"
          href="./custom.css" />
    <style>
        .is-valid~.invalid-feedback {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <form class="was-validated custom-validation">
            <h1 style="color: rgb(11, 156, 11)">
                GeeksforGeeks
            </h1>
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="firstNameInput"
                            class="form-label">
                        First Name
                    </label>
                    <input
                        type="text"
                        class="form-control is-invalid"
                        id="firstNameInput" required />
                    <div class="invalid-feedback">
                        Please enter your first name.
                    </div>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                </div>
                <div class="col-md-6">
                    <label
                        for="lastNameInput"
                        class="form-label">
                        Last Name
                    </label>
                    <input
                        type="text"
                        class="form-control is-invalid"
                        id="lastNameInput" required />
                    <div class="invalid-feedback">
                        Please enter your last name.
                    </div>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                </div>
            </div>
            <div class="row mb-3">
                <div class="col-md-6">
                    <label
                        for="emailInput"
                        class="form-label">
                        Email
                    </label>
                    <input
                        type="email"
                        class="form-control is-invalid"
                        id="emailInput" required />
                    <div class="invalid-feedback">
                        Please enter a valid email
                        address.
                    </div>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                </div>
                <div class="col-md-6">
                    <label
                        for="phoneInput"
                        class="form-label">
                        Phone
                    </label>
                    <input
                        type="tel"
                        class="form-control is-invalid"
                        id="phoneInput" required />
                    <div class="invalid-feedback">
                        Please enter a valid phone
                        number.
                    </div>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                </div>
            </div>
            <div class="mb-3">
                <label
                    for="addressInput"
                    class="form-label">
                    Address
                </label>
                <textarea
                    class="form-control"
                    id="addressInput" required></textarea>
                <div class="invalid-feedback">
                    Please enter your address.
                </div>
                <div class="valid-feedback">
                    Looks good!
                </div>
            </div>
            <div class="mb-3">
                <div class="form-check">
                    <input
                        class="form-check-input"
                        type="checkbox"
                        id="agreeCheck" required />
                    <label
                        class="form-check-label"
                        for="agreeCheck">
                        I agree to the terms and
                        conditions.
                    </label>
                    <div class="invalid-feedback">
                        Please agree to the terms and
                        conditions.
                    </div>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                </div>
            </div>
            <button
                type="submit"
                class="btn btn-primary">
                Register
            </button>
        </form>
    </div>
</body>
   
</html>


CSS




// custom.scss
// Import Bootstrap
@import "./node_modules/bootstrap/scss/bootstrap";
 
@mixin form-validation() {
    .is-valid {
        @include form-validation-state(#0f0);
    }
 
    .is-invalid {
        @include form-validation-state(#f00);
    }
}
 
@mixin form-validation-state($color) {
    border-color: $color;
 
    & ~ .invalid-feedback {
        color: $color;
    }
}
 
$primary-color: #007bff; // Define primary color
 
.container {
    max-width: 800px;
    margin: auto;
}
 
.custom-validation {
    .form-control {
        border: 1px solid #ced4da;
        border-radius: 0.25rem;
        padding: 0.375rem 0.75rem;
        transition: border-color 0.15s ease-in-out,
            box-shadow 0.15s ease-in-out;
 
        &:focus {
            border-color: $primary-color;
            box-shadow: 0 0 0 0.25rem
                rgba(0, 123, 255, 0.25);
        }
 
        @include form-validation();
    }
 
    .invalid-feedback,
    .valid-feedback {
        display: none;
        width: 100%;
        margin-top: 0.25rem;
        font-size: 0.875rem;
 
        &.valid-feedback {
            @include form-validation-state(#28a745);
        }
 
        &.invalid-feedback {
            @include form-validation-state(#dc3545);
        }
    }
 
    .was-validated {
        .form-control.is-valid,
        .form-check-input.is-valid {
            @include form-validation-state(#28a745);
        }
 
        .form-control.is-invalid,
        .form-check-input.is-invalid {
            @include form-validation-state(#dc3545);
        }
 
        .form-control.is-validating + .invalid-feedback,
        .form-check-input.is-validating
            + .invalid-feedback {
            display: block;
        }
 
        .form-control.is-valid + .valid-feedback,
        .form-check-input.is-valid + .valid-feedback {
            display: block;
        }
    }
 
    .form-check-input {
        margin-top: 0.3rem;
    }
 
    .form-check-label {
        margin-left: 1.5rem;
    }
 
    .btn-primary {
        background-color: $primary-color;
        border-color: $primary-color;
 
        &:hover {
            background-color: darken($primary-color, 10%);
            border-color: darken($primary-color, 10%);
        }
    }
}


CSS




/* custom.css*/
form {
    display: flex;
    flex-direction: column;
    align-items: center;
    max-width: 400px;
    margin: 0 auto;
}


Output:

Bootstrap5-Validation-Sass---Google-Chrome-2023-07-19-02-26-51

Validation with feedback messages

Reference: https://getbootstrap.com/docs/5.0/forms/validation/#sass



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads