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.
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.
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:
jqBootstrapValidation.js
file from the project’s official repository or CDN.js
directory (or similar).<script>
tag, ensuring jQuery is included first. For example:<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.
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>
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.
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.
jqBootstrapValidation automatically applies validation based on standard HTML5 input types and attributes. Specifically:
required
attribute: Marks fields as mandatory.type="email"
: Validates email format.type="url"
: Validates URL format.type="number"
: Validates numeric input (within specified range if min
and max
attributes are used).type="tel"
: Basic phone number validation (limited).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.
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.
data-validation-*
attributes: These attributes define the validation rules. For example:
<input type="text" class="form-control" id="name" data-validation="required" data-validation-error-msg="A name is required">
<input type="email" class="form-control" id="email" data-validation="required, email" data-validation-error-msg-email="Please enter a valid email address.">
This shows how to specify multiple rules (required
, email
) using commas as separators.
Supported Rules: jqBootstrapValidation uses the rules supported by jQuery Validate, including required
, email
, url
, number
, min
, max
, minlength
, maxlength
, etc. Consult the jQuery Validate documentation for a comprehensive list.
Custom Rules: Although not directly supported by jqBootstrapValidation’s core, you can extend it by integrating custom rules from jQuery Validate into your project.
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.
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:
.help-block
: This class contains the error message text..has-error
: This class is added to the form-group when there’s an error..has-success
: This class is added to the form-group when the field is valid (can be useful for visual feedback).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.
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');
}; })
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.
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.">
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.
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.">
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.
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.
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.
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
.
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.
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.
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:
.help-block
: This class usually contains the error message text. Styling this will directly affect the appearance of error messages..has-error
: This class is added to the parent <div class="form-group">
when a validation error occurs. Modifying this class allows you to style the entire form group to indicate an error (e.g., changing the background color)..has-success
: Similar to .has-error
, this class is applied when the field is valid. This is often used to provide visual feedback when the user correctly enters the data.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;
}
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.
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.
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).
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.
jqBootstrapValidation exposes several events that you can listen to for custom actions:
validated.bs.jqBootstrapValidation
: Fired after a field is validated.invalid.bs.jqBootstrapValidation
: Fired when a field is invalid.valid.bs.jqBootstrapValidation
: Fired when a field is valid.submit.bs.jqBootstrapValidation
: Fired before the form is submitted.submitSuccess.bs.jqBootstrapValidation
: Fired on successful form validation.submitError.bs.jqBootstrapValidation
: Fired on form validation error.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
.closest('.form-group').addClass('has-success');
$target; })
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.
has-error
or has-success
) are applied as expected. This helps identify if the plugin is functioning correctly.jqBootstrapValidation provides several methods for interacting with the plugin:
jqBootstrapValidation()
: This is the core method to initialize the plugin on a form. It can be called with an options object (see the Options section below) to configure the plugin’s behavior. Example: $("#myForm").jqBootstrapValidation();
isValid()
: This method returns true
if the form is valid and false
otherwise. This can be used to check the form’s validity before submitting it programmatically. Example: var isValid = $("#myForm").isValid();
destroy()
: This method removes the plugin’s functionality from the form. This is useful if you need to dynamically remove validation from a form. Example: $("#myForm").jqBootstrapValidation('destroy');
resetValidation()
: This method resets the validation state of the form. This clears any existing error messages and removes the has-error
class from form groups. Example: $("#myForm").jqBootstrapValidation('resetValidation');
update()
: This method allows you to refresh or re-validate the form. Useful if you’ve dynamically added or modified elements within the form after initializing the plugin. Example: $("#myForm").jqBootstrapValidation('update');
prepareSubmit()
: This method prepares the form for submission, performing final validation checks. It can be used before initiating an AJAX request to ensure that client-side validation passes. Example: $("#myForm").jqBootstrapValidation('prepareSubmit');
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.
jqBootstrapValidation triggers several events that can be used to customize the plugin’s behavior:
validated.bs.jqBootstrapValidation
: Fired after a field is validated. The event object contains a $target
property referencing the validated field’s jQuery object.
invalid.bs.jqBootstrapValidation
: Fired when a field is invalid. The event object contains a $target
property referencing the invalid field’s jQuery object.
valid.bs.jqBootstrapValidation
: Fired when a field is valid. The event object contains a $target
property referencing the valid field’s jQuery object.
submit.bs.jqBootstrapValidation
: Fired before the form is submitted (can be canceled).
submitSuccess.bs.jqBootstrapValidation
: Fired after successful form validation (before submission).
submitError.bs.jqBootstrapValidation
: Fired after form validation fails.
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);
; })
The jqBootstrapValidation()
method accepts an options object to configure the plugin:
submitError
: A callback function that is executed when the form submission fails validation. It receives the form as an argument. This is where you can handle client-side validation errors.
submitSuccess
: A callback function that is executed when form validation is successful. It receives the form as an argument. This is often used to handle form submission via AJAX.
filter
: A selector string to filter elements within the form to apply validation to (this is useful when you have multiple forms on the same page and only want to validate specific forms).
preventSubmit
: A boolean value (default: true
). If set to true
(default), it prevents the default form submission behavior if validation fails.
errorMessage
: A function which takes the $element
and $messageElement
as parameters that returns a customized error message. This is a more advanced method of customizing error messages.
onSuccess
: A function that will be executed once the form has been validated successfully. This function takes the validated form as a parameter.
onFail
: A function that will be executed once a field in the form has failed validation. This function takes the invalid field’s jQuery element as a parameter.
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.
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.
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.
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.
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.