Horje
Bootstrap5 Validation SASS

Bootstrap 5 introduced a new feature to use SASS, a powerful CSS preprocessor, for format validation. SASS allows developers to write maintainable and organized code by providing features such as variables, mixins, maps, and loops. By using these features, users can easily adapt the authentication process and actions to suit the needs of their business and also benefit from code reuse

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 shapes. Adjustments can be used to customize colors, borders, and other visual elements in authentication messages and form controls.
  • Mixins: Mixins are reusable pieces of CSS code that can contain additional styles. In Bootstrap 5 validation, mixins can be used to define and implement common methods for validation scenarios such as success, error, and warning.
  • Maps: Sass maps are key-value pairs that allow you to store and access data. In Bootstrap 5 validation, mappings can be used to define validation methods for various form control types or for custom validation classes.
  • Loops: Loops in Sass allow you to iterate over values ​​and perform actions repeatedly. When it comes to Bootstrap 5 validation, loops can be used to create styles for different validation situations or apply styles to multiple form controls at the same time.
  • Customizing: Bootstrap 5 Verification provides extensive customization options to customize Sass verification methods and actions. Users can tap into pre-defined Sass transformations, mixins, maps, and loop structures to give your documents a unique look and feel.

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

Conclusion : Combining Bootstrap 5 with SASS allows for the flexibility of powerful authentication mechanisms. Using SASS features such as variables, mixins, maps, and loops, developers can tailor the validation process to their business needs to generate maintainable and reusable code The steps provided above show how to override Bootstrap’s default styles and optimize validation messages and form controls. See the official Bootstrap 5 documentation for details.




Reffered: https://www.geeksforgeeks.org


Bootstrap

Related
Bootstrap 5 Grid System SASS Bootstrap 5 Grid System SASS
Bootstrap 5 Checks and Radios Indeterminate Bootstrap 5 Checks and Radios Indeterminate
Bootstrap 5 Grid system options Bootstrap 5 Grid system options
Bootstrap 5 Scrollspy Events Bootstrap 5 Scrollspy Events
Bootstrap 5 Accordion Bootstrap 5 Accordion

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18