Bootstrap - Validation

-

Validation Classes

Bootstrap has two validation classes that can be used on forms to add validation styles and feedback:

  1. .was-validated: This class shows that the form has been validated. When added to a <form> element, it will apply validation styles to all form controls within the form based on their validation state. The .was-validated class is usually added after the form has been submitted and validated.

  2. .needs-validation: This class shows that the form needs validation. When added to a <form> element, it will stop the form from being submitted if any of the form controls are invalid. The .needs-validation class is usually added to the form at the start, before any validation has happened.

To use these validation classes on a form, add the class to the <form> element.

Example: Applying .needs-validation Class

<form class="needs-validation" novalidate>
  <!-- Form controls go here -->
</form>

In the example above, the .needs-validation class is added to the form, showing that it needs validation. The novalidate attribute is also added to turn off the browser's default validation, letting Bootstrap's validation styles and feedback be used instead.

When the form is submitted, you can use JavaScript to add the .was-validated class to the form, which will add the validation styles based on the validation state of each form control.

Example: JavaScript to Add .was-validated Class

const form = document.querySelector('form');
form.addEventListener('submit', function (event) {
  if (!form.checkValidity()) {
    event.preventDefault();
    event.stopPropagation();
  }
  form.classList.add('was-validated');
});

In this JavaScript code, the form's submit event is watched for. If the form is not valid (!form.checkValidity()), the form submission is stopped using event.preventDefault() and event.stopPropagation(). Then, the .was-validated class is added to the form using form.classList.add('was-validated'), which adds the validation styles.

By using these validation classes, you can add Bootstrap's validation styles and feedback to your forms, giving users a way to check their input and fill out forms correctly.

Validation Styles

Bootstrap gives you default validation styles for form controls, which are used when using the validation classes. These styles give visual feedback to users about the validation state of form inputs.

The default validation styles in Bootstrap are:

Valid Inputs Invalid Inputs
Green border color Red border color
Green checkmark icon Red exclamation icon

These styles are automatically used when the .was-validated class is added to the <form> element or when the novalidate attribute is present on the <form> element and the form is submitted.

While the default validation styles are good for many uses, you may want to change them to fit your application's design. Bootstrap lets you do this with CSS.

To change the validation styles, you can use CSS to target the form controls with the .is-valid and .is-invalid classes, which are added by Bootstrap based on the validation state.

Example: Change the border color and icon color for valid inputs

.form-control.is-valid,
.was-validated .form-control:valid {
  border-color: #2ecc71; /* Change the border color */
}

.form-control.is-valid:focus,
.was-validated .form-control:valid:focus {
  box-shadow: 0 0 0 0.2rem rgba(46, 204, 113, 0.25); /* Change the focus shadow color */
}

.form-control.is-valid ~ .valid-feedback,
.form-control.is-valid ~ .valid-tooltip,
.was-validated .form-control:valid ~ .valid-feedback,
.was-validated .form-control:valid ~ .valid-tooltip {
  display: block;
  color: #2ecc71; /* Change the validation message color */
}

Similarly, you can change the styles for invalid inputs:

Example: Change the styles for invalid inputs

.form-control.is-invalid,
.was-validated .form-control:invalid {
  border-color: #e74c3c; /* Change the border color */
}

.form-control.is-invalid:focus,
.was-validated .form-control:invalid:focus {
  box-shadow: 0 0 0 0.2rem rgba(231, 76, 60, 0.25); /* Change the focus shadow color */
}

.form-control.is-invalid ~ .invalid-feedback,
.form-control.is-invalid ~ .invalid-tooltip,
.was-validated .form-control:invalid ~ .invalid-feedback,
.was-validated .form-control:invalid ~ .invalid-tooltip {
  display: block;
  color: #e74c3c; /* Change the validation message color */
}

By changing the CSS for the validation classes, you can change how the validation styles look, while keeping the functions provided by Bootstrap. This lets you have a validation experience that is both good for users and matches your application's style.

Validation States

Bootstrap has classes for showing feedback messages to users based on the validation state of form controls. These feedback messages give users more information about why a form control is valid or invalid, helping them fill out the form correctly.

Valid Feedback

Class Description
.valid-feedback Shows a feedback message when a form control is valid. The message is shown below the form control and is hidden by default. It becomes visible when the form control has the .is-valid class or when the form has the .was-validated class and the form control is valid.

To use the .valid-feedback class, add a <div> or <span> element with the class directly after the form control.

Valid Feedback Example

<div class="form-group">
  <label for="inputEmail">Email</label>
  <input type="email" class="form-control" id="inputEmail" required>
  <div class="valid-feedback">
    Looks good!
  </div>
</div>

Invalid Feedback

Class Description
.invalid-feedback Shows a feedback message when a form control is invalid. Like .valid-feedback, the message is shown below the form control and is hidden by default. It becomes visible when the form control has the .is-invalid class or when the form has the .was-validated class and the form control is invalid.

To use the .invalid-feedback class, add a <div> or <span> element with the class directly after the form control.

Invalid Feedback Example

<div class="form-group">
  <label for="inputPassword">Password</label>
  <input type="password" class="form-control" id="inputPassword" required>
  <div class="invalid-feedback">
    Please provide a password.
  </div>
</div>

Bootstrap handles showing and hiding the feedback messages based on the validation state of the form controls. When a form control is valid and has the .is-valid class, the .valid-feedback message will be shown. When a form control is invalid and has the .is-invalid class, the .invalid-feedback message will be shown.

By using these validation state classes, you can give users helpful feedback about the validity of their form input, guiding them to fill out the form correctly and submit it.

Validation Methods

Bootstrap supports two methods for validating forms: built-in HTML5 validation and custom Bootstrap validation.

Built-in HTML5 Validation

HTML5 has several validation attributes that you can use on form controls to validate user input. These attributes include:

Attribute Description
required Makes the form control required, not letting the form be submitted if the control is empty.
min and max Sets the minimum and maximum values for number inputs.
minlength and maxlength Sets the minimum and maximum length for text inputs.
pattern Specifies a regular expression pattern that the input must match.
type Sets the type of the input, like email, url, or number, which adds built-in validation for those types.

To use HTML5 validation with Bootstrap, add the validation attributes to your form controls.

HTML5 Validation Example

<div class="form-group">
  <label for="inputEmail">Email</label>
  <input type="email" class="form-control" id="inputEmail" required>
  <div class="invalid-feedback">
    Please provide a valid email address.
  </div>
</div>

The type="email" attribute validates that the input is a valid email address, and the required attribute makes the field required.

To use Bootstrap's validation styles with HTML5 validation, add the novalidate attribute to your <form> element. This turns off the browser's default validation popup, letting Bootstrap's validation styles be used instead.

Example: Bootstrap Validation Styles

<form novalidate>
  <!-- Form controls go here -->
</form>

Custom Bootstrap Validation

In addition to HTML5 validation, Bootstrap lets you write custom validation rules using JavaScript. This is useful when you need more complex validation than what HTML5 validation provides.

To write custom validation rules, you can use the Bootstrap Validator plugin or write your own validation code.

Custom Validation Example

<div class="form-group">
  <label for="inputPhone">Phone Number</label>
  <input type="text" class="form-control" id="inputPhone" required>
  <div class="invalid-feedback">
    Please provide a valid phone number (10 digits).
  </div>
</div>
const form = document.querySelector('form');
const phoneInput = document.getElementById('inputPhone');

phoneInput.addEventListener('input', function () {
  if (this.value.length === 10) {
    this.setCustomValidity('');
  } else {
    this.setCustomValidity('Phone number must be 10 digits.');
  }
});

form.addEventListener('submit', function (event) {
  if (!form.checkValidity()) {
    event.preventDefault();
    event.stopPropagation();
  }
  form.classList.add('was-validated');
});

For the phone number input field, an input event listener checks if the phone number is exactly 10 digits. If valid, the custom validity message is cleared. Otherwise, an error message is set.

A submit event listener checks the form's validity using form.checkValidity(). If the form is not valid, the submission is prevented, and the .was-validated class is added to show validation styles.

By using custom validation with JavaScript, you can add complex validation rules to your forms beyond what HTML5 validation provides. This gives you more control over the user input and helps make sure that the data submitted is valid.

Server-side Validation

While client-side validation with HTML5 and JavaScript is important for giving users quick feedback and checking input is in the right format, it's also essential to add server-side validation to your forms.

Server-side validation is the process of checking user input on the server after the form has been submitted. This is important because client-side validation can be turned off or tricked by users, so you can't trust it completely. Server-side validation acts as a second line of defense, making sure that the data you get is valid and safe before it's stored or used.

Here are some reasons why server-side validation is important:

Reason Explanation
Security Users can disable JavaScript or change form data after it's validated on the client side. Server-side validation makes sure the data is checked again before it's used, preventing potential security issues.
Data integrity Server-side validation checks that the data matches what's expected and follows any business rules or constraints. This makes sure that the data stored in your database is accurate and consistent.
Feedback If a form submission fails server-side validation, you can send back feedback to the user to let them know what went wrong and how to fix it.

When using Bootstrap for form validation, you can add server-side validation in a few ways:

  1. Ajax validation: Before the form is submitted, you can use Ajax to send form data to the server for validation. If the server returns any validation errors, you can show them to the user using Bootstrap's validation classes and feedback elements.

  2. Post-submission validation: After the form is submitted, you can check the form data on the server. If there are any validation errors, you can send the user back to the form page with the errors shown using Bootstrap's validation classes and feedback elements.

  3. Hybrid approach: You can use a mix of client-side and server-side validation, using client-side validation to give users quick feedback and catch common errors, and server-side validation to do a final check and handle more complex validation rules.

Example: Server-side validation errors using Bootstrap's validation classes

<!-- Form submitted with server-side validation errors -->
<form class="was-validated">
  <div class="form-group">
    <label for="inputEmail">Email</label>
    <input type="email" class="form-control is-invalid" id="inputEmail" required>
    <div class="invalid-feedback">
      Please provide a valid email address.
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword">Password</label>
    <input type="password" class="form-control is-invalid" id="inputPassword" required>
    <div class="invalid-feedback">
      Password must be at least 8 characters long.
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

By adding server-side validation to your Bootstrap forms, you can make sure that the data you receive is valid, secure, and follows your application's rules. This helps protect your application and database, and gives users clear feedback if there are any issues with their form submission.

Validation Examples

Bootstrap validation is a way to make sure user input is correct and follows the format you expect. Let's look at some examples of how to use Bootstrap validation in different situations.

Basic Form Validation Example

Example: Basic Form Validation

<form class="needs-validation" novalidate>
  <div class="form-group">
    <label for="inputName">Name</label>
    <input type="text" class="form-control" id="inputName" required>
    <div class="valid-feedback">
      Looks good!
    </div>
    <div class="invalid-feedback">
      Please provide your name.
    </div>
  </div>
  <div class="form-group">
    <label for="inputEmail">Email</label>
    <input type="email" class="form-control" id="inputEmail" required>
    <div class="valid-feedback">
      Looks good!
    </div>
    <div class="invalid-feedback">
      Please provide a valid email address.
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

This form has two fields: a name field and an email field. Both fields are marked as required using the required attribute. The form also has the needs-validation class, which enables Bootstrap validation, and the novalidate attribute, which turns off the browser's default validation.

When you submit the form, Bootstrap will check if you filled out the fields and if the email field contains a valid email address. If a field is valid, you will see the .valid-feedback message. If a field is invalid, you will see the .invalid-feedback message.

Validating Different Form Input Types

Bootstrap validation works with all the different form input types, like text, email, number, date, etc.

Example: Validating Different Input Types

<form class="needs-validation" novalidate>
  <div class="form-group">
    <label for="inputText">Text Input</label>
    <input type="text" class="form-control" id="inputText" required>
    <div class="invalid-feedback">
      Please fill out this field.
    </div>
  </div>
  <div class="form-group">
    <label for="inputEmail">Email Input</label>
    <input type="email" class="form-control" id="inputEmail" required>
    <div class="invalid-feedback">
      Please provide a valid email address.
    </div>
  </div>
  <div class="form-group">
    <label for="inputNumber">Number Input</label>
    <input type="number" class="form-control" id="inputNumber" min="1" max="10" required>
    <div class="invalid-feedback">
      Please provide a number between 1 and 10.
    </div>
  </div>
  <div class="form-group">
    <label for="inputDate">Date Input</label>
    <input type="date" class="form-control" id="inputDate" required>
    <div class="invalid-feedback">
      Please select a date.
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

This form shows how to validate text, email, number, and date inputs. The email input will be checked for a valid email format. The number input has min and max attributes to limit the allowed value range. The date input will make sure you selected a date.

Custom Validation Example

For more complex validation requirements, you can write custom validation rules in JavaScript.

Example: Custom Validation

<form class="needs-validation" novalidate>
  <div class="form-group">
    <label for="inputPassword">Password</label>
    <input type="password" class="form-control" id="inputPassword" required>
    <div class="invalid-feedback">
      Password must be at least 8 characters long and contain at least one number and one uppercase letter.
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
const form = document.querySelector('form');
const passwordInput = document.getElementById('inputPassword');

const validatePassword = (password) => {
  const regex = /^(?=.*\d)(?=.*[A-Z])[0-9a-zA-Z]{8,}$/;
  return regex.test(password);
};

passwordInput.addEventListener('input', function () {
  if (validatePassword(this.value)) {
    this.setCustomValidity('');
  } else {
    this.setCustomValidity('Password must be at least 8 characters long and contain at least one number and one uppercase letter.');
  }
});

form.addEventListener('submit', function (event) {
  if (!form.checkValidity()) {
    event.preventDefault();
    event.stopPropagation();
  }
  form.classList.add('was-validated');
});

The password field is validated using a custom validation function validatePassword(). This function checks if the password is at least 8 characters long and contains at least one number and one uppercase letter using a regular expression.

An input event listener on the password field checks the password validity whenever you change the password. If the password is valid, the custom validity message is cleared. If the password is invalid, the custom validity message is set to explain the password requirements.

A submit event listener on the form checks the overall form validity before submission. If the form is invalid, the submission is prevented, and the was-validated class is added to show the validation feedback.

These examples show the flexibility and power of Bootstrap's validation system. Bootstrap provides the tools and classes to make it easy to add validation to your forms.