Home > Software design >  Bootstrap 5 Form Validation
Bootstrap 5 Form Validation

Time:01-23

I'm using Bootstrap 5 forms where I came across this strange behaviour that I gave was-validated class to form which displays the red border across the input field but when I enter something in the text box is automatically removed that red border and replaces it with green border. WHERE THIS AUTOMATIC BEHAVIOUR IS COMING FROM GIVEN THAT I'M NOT USING JS.

<form >
    Your Name:
    <input type="text"  required>
    <button type="submit" >Submit</button>
</form>

CodePudding user response:

This behaviour is coming from the Bootstrap CSS classes that are automatically applied to form controls when they are used in a form.

When the was-validated class is added to a form, Bootstrap will automatically apply the is-valid class to form controls that are filled in correctly, and the is-invalid class to form controls that are not filled in correctly.

CodePudding user response:

By default, the browser is doing form validation, based on the input’s required state, the type attribute, and other attributes depending on type.

Bootstrap then uses :invalid and other pseudo-classes to assign styles.

As you can read on the Bootstrap Form Validation docs

Here’s how form validation works with Bootstrap:

HTML form validation is applied via CSS’s two pseudo-classes, :invalid and :valid. It applies to , , and elements.

The section Browser defaults then provides an example on how to rely on the browser’s validation, if you do not want to run javascript validations.

The bottom line is: Do not assign was-validated if you do not validate with JavaScript.

<form>
    <label for="validationDefault05" >Zip</label>
    <input type="text"  id="validationDefault05" required pattern="[0-9]*">
  • Related