jqBootstrapValidation - Documentation

Introduction

What is jqBootstrapValidation?

jqBootstrapValidation is a jQuery plugin that provides a simple yet powerful way to add validation to forms built with Bootstrap. It leverages Bootstrap’s styling to provide visually appealing and user-friendly feedback on form submissions. Unlike other validation plugins, it focuses on providing a lightweight and unobtrusive solution, integrating seamlessly with Bootstrap’s existing form elements and styles. It handles both client-side and server-side validation workflows, providing feedback immediately to the user without requiring a full page reload.

Key Features

Browser Compatibility

jqBootstrapValidation aims for broad browser compatibility. It is thoroughly tested on modern browsers including:

Older browsers might require polyfills for certain features. While older browsers might function, full support is not guaranteed for versions significantly behind the latest releases.

Installation

jqBootstrapValidation can be easily integrated into your project using several methods:

1. Using a CDN: Include the following <script> tag in your HTML file’s <head> section, ensuring jQuery is already included:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.min.js"></script>
<script src="path/to/jqBootstrapValidation.js"></script> 

Replace "path/to/jqBootstrapValidation.js" with the actual path to the downloaded jqBootstrapValidation.js file.

2. Download and Include:

<script src="js/jquery.min.js"></script>
<script src="js/jqBootstrapValidation.js"></script>

3. Using a Package Manager (npm): If using npm or yarn, install the package and then include it in your build process as per your chosen framework’s instructions. (Note: Availability through npm may vary depending on the project’s current packaging.)

After including the script, initialize the plugin on your form. Refer to the usage instructions for details on configuring validation rules.

Getting Started

Including the Library

Before you can use jqBootstrapValidation, you need to include the necessary JavaScript files in your HTML document. This includes jQuery itself, and then the jqBootstrapValidation plugin. Ensure jQuery is included before the jqBootstrapValidation script. You can achieve this using CDNs or by downloading the files and referencing them locally.

Using a CDN (Recommended):

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>  <!-- Or a later version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.min.js"></script>
<script src="path/to/jqBootstrapValidation.js"></script> 

Remember to replace "path/to/jqBootstrapValidation.js" with the correct path if you’re not using a CDN for the plugin. Always prioritize using the latest stable jQuery version.

Local Files: If you’ve downloaded the files, adjust the paths accordingly to reflect your project’s structure. For instance:

<script src="js/jquery.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/jquery.validate.unobtrusive.min.js"></script>
<script src="js/jqBootstrapValidation.js"></script>

Basic Usage

Once included, initializing the plugin is straightforward. Simply call the jqBootstrapValidation() method on your form element after the page has fully loaded (typically within a $(document).ready() function).

$(document).ready(function() {
  $("form").jqBootstrapValidation();
});

This will apply validation to all fields within the form. By default, it will use Bootstrap’s styling to display error messages. More sophisticated configurations are detailed in later sections.

HTML Structure

jqBootstrapValidation works with standard Bootstrap forms. You don’t need any special HTML attributes beyond those you would normally use with Bootstrap for form building. The plugin automatically detects form elements and applies validation based on the element type and any existing attributes (like required). A simple example:

<form id="myForm">
  <div class="form-group">
    <label for="name">Name:</label>
    <input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name.">
  </div>
  <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email address.">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Notice the use of Bootstrap’s form-group class and the required attribute. The data-validation-required-message attribute allows you to customize the error message displayed for required fields.

Default Validation

jqBootstrapValidation automatically applies validation based on standard HTML5 input types and attributes. Specifically:

For more advanced validation scenarios or custom rules, refer to the sections on customizing error messages and adding custom validation rules. The plugin’s default behavior provides a robust baseline for most basic form validation needs.

Configuration Options

Specifying Validation Rules

While jqBootstrapValidation provides default validation based on HTML5 attributes, you can extend and customize this behavior. You primarily achieve this using data attributes within your form elements. The plugin leverages the jQuery Validate plugin under the hood.

Custom Error Messages

Override default error messages by using the data-validation-error-msg attribute. You can create specific error messages for each rule by using the data-validation-error-msg-{rule} attribute.

<input type="text" class="form-control" id="name" data-validation="required, minlength" data-validation-error-msg="This field is required." data-validation-error-msg-minlength="Name must be at least 5 characters.">

This sets a general error message and a specific message for the minlength rule.

Styling the Validation Feedback

jqBootstrapValidation uses Bootstrap’s default styling for error messages. To customize the appearance, you need to override Bootstrap’s CSS classes. Common classes to target include:

Modify the styles within your custom CSS file to change colors, fonts, positioning, etc., of these classes. Avoid directly modifying Bootstrap’s core CSS files to maintain ease of updates.

Conditional Validation

You can implement conditional validation using jQuery’s functionality and the data-validation attributes. For example, you might want a field to be required only if another field has a certain value. You would achieve this by using JavaScript to dynamically add or remove the required data attribute or the data-validation attributes based on user interactions.

$('#field1').change(function() {
  if ($(this).val() === 'yes') {
    $('#field2').attr('data-validation', 'required');
  } else {
    $('#field2').removeAttr('data-validation');
  }
});

Advanced Configuration Options

While basic usage involves simply calling jqBootstrapValidation(), you can pass an options object to further fine-tune the plugin’s behavior:

$("form").jqBootstrapValidation({
  submitError: function($form) {
    // Handle submission errors
  },
  submitSuccess: function($form) {
    // Handle successful submission
  },
  // Add other options as needed... refer to the plugin's documentation for a full list
});

The available options allow you to customize various aspects, such as how errors are handled, specific messages, and even completely replace the default form submission mechanism. The specific options and their usage should be referred to in the plugin’s detailed documentation or source code.

Validation Rules

Required Fields

The simplest validation is ensuring a field is filled in. This is achieved using the required attribute in your HTML, or the data-validation="required" attribute.

<input type="text" class="form-control" id="name" required>  <!-- HTML5 required attribute -->
<input type="text" class="form-control" id="name" data-validation="required"> <!-- jqBootstrapValidation data attribute -->

Both methods achieve the same result. The plugin will display an error message if the field is left empty. You can customize the error message using data-validation-required-message.

<input type="text" class="form-control" id="name" data-validation="required" data-validation-required-message="Please enter your name.">

Email Validation

For email fields, use the email rule. The plugin uses a regular expression to check the format.

<input type="email" class="form-control" id="email" data-validation="email" data-validation-error-msg="Please enter a valid email address.">

This adds the email validation to the field. The data-validation-error-msg provides a custom error message. Note that HTML5’s built-in email type also provides basic validation, but the plugin offers more granular control and customization.

URL Validation

Similar to email, URL validation is handled by the url rule.

<input type="url" class="form-control" id="website" data-validation="url" data-validation-error-msg="Please enter a valid URL.">

Number Validation

For numeric fields, use the number rule. You can optionally combine it with min and max to specify a range.

<input type="number" class="form-control" id="age" data-validation="number, min[18], max[100]" data-validation-error-msg="Please enter a valid number between 18 and 100.">

This ensures the input is a number between 18 and 100 (inclusive). min and max are inclusive.

Minimum and Maximum Length

Control the length of text fields using minlength and maxlength.

<input type="text" class="form-control" id="password" data-validation="minlength[8], maxlength[20]" data-validation-error-msg-minlength="Password must be at least 8 characters." data-validation-error-msg-maxlength="Password cannot exceed 20 characters.">

This ensures the password is between 8 and 20 characters long. Individual error messages are provided for each rule.

Custom Regular Expressions

For validation beyond the built-in rules, use the regexp rule with a custom regular expression.

<input type="text" class="form-control" id="postalCode" data-validation="regexp[^\s]{5}" data-validation-error-msg="Invalid postal code format.">

This example checks for a 5-digit postal code with no spaces using a regular expression. Remember to escape special characters within the regex string as needed.

Matching Fields

To ensure two fields match (e.g., password confirmation), use the confirmation rule, referencing the ID of the field to match.

<input type="password" class="form-control" id="password" data-validation="required">
<input type="password" class="form-control" id="confirmPassword" data-validation="confirmation[password]" data-validation-error-msg="Passwords do not match.">

This validates that confirmPassword matches the value in password.

File Upload Validation

jqBootstrapValidation doesn’t directly validate file uploads. This type of validation typically requires server-side handling. However, client-side checks for file type or size can be performed before submission using JavaScript. The plugin itself doesn’t provide this functionality, but you can implement this separately. You can add additional checks using JavaScript to improve user experience by pre-validating aspects of the file before sending it to the server.

Styling and Customization

Customizing Error Messages

jqBootstrapValidation allows flexible customization of error messages. The most straightforward way is using the data-validation-error-msg and data-validation-error-msg-{rule} attributes directly within your HTML form fields. These attributes allow you to specify custom messages for individual validation rules or provide a general error message.

<input type="text" class="form-control" id="name" data-validation="required, minlength[3]" 
       data-validation-error-msg="Please fill in this field." 
       data-validation-error-msg-minlength="Name must be at least 3 characters.">

In this example, a general message is displayed if the field is not filled at all, and a more specific message is shown if the minimum length requirement isn’t met. You can customize messages for every rule applied to the input field this way.

Adding Custom CSS

To significantly alter the visual style of the validation feedback (error and success messages), you should create custom CSS rules targeting the classes that jqBootstrapValidation uses. The primary classes you would modify are:

Add your custom CSS rules to a separate stylesheet and include it in your HTML. Ensure your custom CSS is loaded after Bootstrap’s CSS to properly override default styles. Example:

.help-block {
  color: red;
  font-weight: bold;
}

.has-error .form-control {
  border-color: red;
}

.has-success .form-control {
  border-color: green;
}

Integrating with Bootstrap Themes

jqBootstrapValidation is designed to work seamlessly with Bootstrap’s default styling. Because it uses Bootstrap’s classes for styling, integrating it with different Bootstrap themes is generally straightforward. The visual feedback will automatically adapt to the colors and styles defined in the chosen theme. However, significant variations in theme structure might necessitate minor CSS adjustments to ensure consistency between the theme and the plugin’s styling.

Using Custom Icons

While the plugin doesn’t include built-in icon support, you can easily add icons (like Font Awesome or similar icon sets) to your error messages or form groups to enhance the visual feedback. This requires adding the relevant icon classes alongside your CSS styling. For example, using Font Awesome:

.has-error .form-control {
  border-color: red;
}

.has-error .form-group::before { /* adds an icon before the form-group */
  content: "\f06a"; /* FontAwesome error icon */
  display: inline-block;
  margin-right: 5px;
  color: red;
}

Remember to include the chosen icon library (like Font Awesome) in your project. You can place the icon before or after the form element as needed by adjusting the CSS selector and content property. Adjust the CSS to integrate seamlessly with your chosen theme.

Advanced Usage

Handling AJAX Validation

While jqBootstrapValidation primarily focuses on client-side validation, it seamlessly integrates with AJAX-based server-side validation. The plugin doesn’t directly handle AJAX requests; you need to manage them separately using jQuery’s $.ajax() or a similar method.

The key is to utilize the submitSuccess and submitError callbacks within the plugin’s configuration:

$("form").jqBootstrapValidation({
  submitSuccess: function(form) {
    // Form data is valid; send via AJAX
    $.ajax({
      url: form.attr('action'),
      type: form.attr('method'),
      data: form.serialize(),
      success: function(response) {
        // Handle successful server-side validation
        // Display success message, redirect, etc.
      },
      error: function(xhr, status, error) {
        // Handle server-side validation errors
        // Display error messages received from the server
        var errors = JSON.parse(xhr.responseText); // Assuming server returns JSON errors
        $.each(errors, function(field, messages) {
          // Update form elements with appropriate error messages
        });
      }
    });
    return false; // Prevent default form submission
  },
  submitError: function(form) {
    // Handle client-side validation errors (already handled by the plugin)
  }
});

In this example, the submitSuccess callback sends the form data via AJAX. The success callback handles a successful response, and the error callback handles server-side errors, allowing you to display server-returned error messages. Remember to parse the server’s response appropriately (here assumed to be JSON).

Programmatic Validation

Instead of relying solely on user input to trigger validation, you can programmatically validate the form using the isValid() method:

var isValid = $("#myForm").isValid();
if (isValid) {
  // Form is valid; proceed with submission or other actions
} else {
  // Form is invalid; handle accordingly
}

This allows for validation before explicitly submitting the form, perhaps in response to a button click or other events. This is particularly useful when you want to check the validity of the form before performing an action other than submission.

Event Handling

jqBootstrapValidation exposes several events that you can listen to for custom actions:

These events can be used to trigger custom behaviors (e.g., highlighting fields, displaying custom messages, or preventing submission under specific circumstances).

$("#myForm").on('valid.bs.jqBootstrapValidation', function(event, $target) {
    // Handle valid field event
    $target.closest('.form-group').addClass('has-success');
});

Integration with other Javascript Libraries

jqBootstrapValidation is designed to work well with other JavaScript libraries, particularly those that don’t directly conflict with jQuery or the form submission process. However, ensure that other libraries don’t override or interfere with the plugin’s functionality or the standard form submission behavior. Thorough testing is crucial when integrating it into larger applications.

Debugging Tips and Troubleshooting

API Reference

Methods

jqBootstrapValidation provides several methods for interacting with the plugin:

It’s crucial to call these methods on a jQuery object representing the form element. Always refer to the plugin’s documentation for the most up-to-date information and any additional methods that might be available in newer releases.

Events

jqBootstrapValidation triggers several events that can be used to customize the plugin’s behavior:

These events provide a way to implement custom actions based on the validation status. Use the on() method in jQuery to bind event handlers. Example:

$("#myForm").on('valid.bs.jqBootstrapValidation', function(event, $target){
  console.log("Field is valid:", $target);
});

Options

The jqBootstrapValidation() method accepts an options object to configure the plugin:

Remember to consult the plugin’s documentation for the most current and complete list of options and their functionalities. Not all options might be relevant or necessary for every application. The options detailed here represent the most commonly used and useful ones.

Examples

Simple Form Validation

This example demonstrates basic form validation using jqBootstrapValidation. It includes required fields and email validation.

<!DOCTYPE html>
<html>
<head>
  <title>Simple Form Validation</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.min.js"></script>
  <script src="path/to/jqBootstrapValidation.js"></script> 
  <script>
    $(document).ready(function() {
      $("form").jqBootstrapValidation();
    });
  </script>
</head>
<body>
  <div class="container">
    <form id="simpleForm">
      <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" id="name" required data-validation-required-message="Please enter your name">
      </div>
      <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" id="email" required data-validation-required-message="Please enter your email">
      </div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
  </div>
</body>
</html>

Remember to replace "path/to/jqBootstrapValidation.js" with the actual path to the plugin file. This example utilizes Bootstrap’s styling for the form and error messages.

Complex Form with Custom Rules

This example shows a more complex form with custom validation rules and error messages. It uses a custom regular expression to validate a phone number.

<form id="complexForm">
  <div class="form-group">
    <label for="phone">Phone:</label>
    <input type="text" class="form-control" id="phone" data-validation="regexp[0-9]{10}" data-validation-error-msg="Please enter a valid 10-digit phone number.">
  </div>
  <div class="form-group">
    <label for="password">Password:</label>
    <input type="password" class="form-control" id="password" data-validation="required, minlength[8]" data-validation-error-msg-minlength="Password must be at least 8 characters.">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

This example demonstrates the usage of custom regular expressions and more detailed error messages. You would need to include the necessary JavaScript and CSS files as shown in the previous example.

AJAX Validation Example

This example showcases how to integrate AJAX validation with jqBootstrapValidation. This is a simplified illustration and requires a server-side component to handle the AJAX request and validation.

$("#ajaxForm").jqBootstrapValidation({
  submitSuccess: function(form) {
    $.ajax({
      url: "/validate", // Replace with your server-side endpoint
      type: "POST",
      data: form.serialize(),
      success: function(response) {
        // Handle successful validation
        alert("Form submitted successfully!");
      },
      error: function(xhr, status, error) {
        // Handle validation errors
        var errors = JSON.parse(xhr.responseText);
        $.each(errors, function(field, message) {
          $("#" + field).addClass("is-invalid").next(".invalid-feedback").text(message);
        });
      }
    });
    return false;
  }
});

This requires a backend endpoint (/validate in this example) that processes the form data and returns a JSON response indicating success or failure, along with error messages.

Integration with Bootstrap Forms

jqBootstrapValidation works seamlessly with standard Bootstrap forms. No special HTML structure is required beyond the standard Bootstrap form elements. The plugin automatically integrates with Bootstrap’s styling and error message placement. The examples above already demonstrate this integration. Ensure that you include Bootstrap’s CSS and JS files in your project, and use Bootstrap’s form classes (form-group, form-control, etc.) in your HTML to get the full benefit of this integration. The examples above already illustrate this, demonstrating how effortlessly the validation integrates with a standard Bootstrap form structure.