v0.5.3 is released on 2014.11.05!

API

Collection of public methods that help you do additional jobs

Improve it on Github

Usage

After initializing the form with the plugin using $(form).bootstrapValidator(options), there are two ways to call the plugin method:

// Get plugin instance
var bootstrapValidator = $(form).data('bootstrapValidator');

// and then call method
bootstrapValidator.methodName(parameters)

or:

$(form).bootstrapValidator(methodName, parameters);

The first way mostly returns the BootstrapValidator instance, meanwhile the second one always returns the jQuery object representing the form.

So, it's possible to chain methods as below:

// The first way
$(form)
    .data('bootstrapValidator')
    .updateStatus('birthday', 'NOT_VALIDATED')
    .validateField('birthday');

// The second one
$(form)
    .bootstrapValidator('updateStatus', 'birthday', 'NOT_VALIDATED')
    .bootstrapValidator('validateField', 'birthday');

API

Below is the list of public methods provided by the plugin.

The methods use the same format as following:

methodName()

methodName(requiredParameter*, optionalParameter, ...): Type of return value — The purpose of method

addField

addField(field*, options): BootstrapValidator — Add a new field.

Parameter Type Description
field String|jQuery The field name or field element
options Object The field options.
If it is not defined, the options are merged by:
  • Options which are parsed from HTML attributes of field
  • The current options which are set when calling the plugin

If you want to do additional task after adding new field, then trigger the added.field.bv event:

$(document).ready(function() {
    $(form)
        .bootstrapValidator(options)
        .on('added.field.bv', function(e, data) {
            // $(e.target)  --> The form instance
            // $(e.target).data('bootstrapValidator')
            //              --> The BootstrapValidator instance

            // data.field   --> The field name
            // data.element --> The new field element
            // data.options --> The new field options

            // Do something ...
        });
});

Example

defaultSubmit

defaultSubmit(): BootstrapValidator — Submit the form using default submission.

It also does not perform any validations when submitting the form. It might be used when you want to submit the form right inside the custom submit handler.

destroy

destroy() — Destroy the plugin.

It will remove all error messages, feedback icons as well as turning off the events created by the plugin.

disableSubmitButtons

disableSubmitButtons(disabled): BootstrapValidator — Disable or enable the submit buttons

Parameter Type Description
disabled Boolean Can be true or false

Example

enableFieldValidators

enableFieldValidators(field*, enabled*, validator): BootstrapValidator — Enable, disable validators to given field

Parameter Type Description
field String The field name
enabled Boolean If true, enable field validators. If false, disable field validators
validator String The validator name. If it is not set, all field validators will be enabled or disabled

Example

getDynamicOption

getDynamicOption(field*, option*): String — Returns the option value which can be set dynamically.

For example, the zipCode validator has country option that can be changed dynamically a select element.

Parameter Type Description
field String|jQuery The field name or element
option String The dynamic option

getFieldElements

getFieldElements(field): jQuery[] — Retrieve the field elements by given name.
Returns array of jQuery element representing the field, or null if the fields are not found.

Parameter Type Description
field String The field name

getInvalidFields

getInvalidFields(): jQuery[] — Returns the list of invalid fields.

getMessages

getMessages(field, validator): String[] — Get the error messages.

Parameter Type Description
field String|jQuery The field name or field element
If the field is not defined, the method returns all error messages of all fields
validator String The name of validator
If the validator is not defined, the method returns error messages of all validators.

Example

getOptions

getOptions(field, validator, option): String|Object — Get the field options.

Parameter Type Description
field String|jQuery The field name or field element
If the field is not defined, the method returns the form options.
validator String The name of validator
If the validator is not defined, the method returns all field options.
option String The option name
If it is not defined, the method returns options of given validator

getSubmitButton

getSubmitButton(): jQuery — Returns a jQuery element presenting the clicked submit button. Returns null if the submit button isn't clicked.

isValid

isValid(): Boolean — Returns true if all form fields are valid. Otherwise, returns false.

Ensure that the validate method is already called after calling this one.

isValidContainer

isValidContainer(container*): Boolean — Returns true if all fields in the container are valid. Otherwise, returns false.

It's useful when working with a wizard-like such as tab, collapse.

Parameter Type Description
container String|jQuery The container selector or container element

isValidField

isValidField(field*): Boolean — Check whether the field is valid or not. Returns true if all validators of field pass. Otherwise, returns false.

Parameter Type Description
field String|jQuery The field name or field element

removeField

removeField(field*): BootstrapValidator — Remove given field

Parameter Type Description
field String|jQuery The field name or field element

By triggering the removed.field.bv event, you can perform additional task after removing given field:

$(document).ready(function() {
    $(form)
        .bootstrapValidator(options)
        .on('removed.field.bv', function(e, data) {
            // $(e.target)  --> The form instance
            // $(e.target).data('bootstrapValidator')
            //              --> The BootstrapValidator instance

            // data.field   --> The field name
            // data.element --> The new field element

            // Do something ...
        });
});

Example

resetField

resetField(field*, resetValue): BootstrapValidator — Reset given field. It hides the error messages and feedback icons.

Parameter Type Description
field String|jQuery The field name or field element
resetValue Boolean If true, the method resets field value to empty or remove checked/selected attribute (for radio and checkbox).

resetForm

resetForm(resetFormData): BootstrapValidator — Reset form. It hides all error elements and feedback icons. All the fields are marked as not validated yet.

Parameter Type Description
resetFormData Boolean If true, the method resets the fields which have validator rules.
$(form).bootstrapValidator(options);
$(form).data('bootstrapValidator').resetForm();

revalidateField

revalidateField(field*): BootstrapValidator — Revalidate given field.

It's used when you need to revalidate the field which its value is updated by other plugin.

By default, the plugin doesn't re-validate a field once it is already validated and marked as a valid one. When using with other plugins, the field value is changed and therefore need to be re-validated.

Behind the scenes, the method is equivalent to:

$(form).data('bootstrapValidator')
    .updateStatus(field, 'NOT_VALIDATED')
    .validateField(field);

// Or
$(form).bootstrapValidator('updateStatus', field, 'NOT_VALIDATED')
       .bootstrapValidator('validateField', field);
Parameter Type Description
field String|jQuery The field name or field element

Examples

The following example describes how to re-validate a field which uses with Boostrap Datetime Picker:

<link href="/vendor/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<style type="text/css">
#datetimeForm .has-feedback .form-control-feedback {
    top: 0;
    right: -15px;
}
</style>

<script src="//oss.maxcdn.com/momentjs/2.8.2/moment.min.js"></script>
<script src="/vendor/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>

<form id="datetimeForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-3 control-label">DateTime Picker</label>
        <div class="col-sm-5">
            <div class="input-group date" id="datetimePicker">
                <input type="text" class="form-control" name="datetimePicker" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
</form>
$(document).ready(function() {
    // updateStatus() example
    $('#datetimePicker').datetimepicker();

    $('#datetimeForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            datetimePicker: {
                validators: {
                    notEmpty: {
                        message: 'The date is required and cannot be empty'
                    },
                    date: {
                        format: 'MM/DD/YYYY h:m A'
                    }
                }
            }
        }
    });

    $('#datetimePicker')
        .on('dp.change dp.show', function (e) {
            // Revalidate the date when user change it
            $('#datetimeForm').bootstrapValidator('revalidateField', 'datetimePicker');
        });
});

updateMessage

updateMessage(field*, validator*, message*): BootstrapValidator — Update the error message.

Parameter Type Description
field String|jQuery The field name or field element
validator String The validator name
message String The error message

updateOption

updateOption(field*, validator*, option*, value*): BootstrapValidator — Update the option of a specific validator.

Parameter Type Description
field String|jQuery The field name or field element
validator String The validator name
option String The option name
value String The option value

updateStatus

updateStatus(field*, status*, validator): BootstrapValidator — Update validator result for given field

Parameter Type Description
field String|jQuery The field name or field element
status String Can be NOT_VALIDATED, VALIDATING, INVALID or VALID
validator String The validator name. If null, the method updates validity result for all validators

Example

The updateStatus method might be used when a field validity is effected by other filed.

For example, the form below asks user for credit card expiration. The expiration is valid if it is in the range of next month and next 10 year.

<form id="paymentForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-3 control-label">Expiration</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Month" name="expMonth" />
        </div>
        <div class="col-sm-3">
            <input type="text" class="form-control" placeholder="Year" name="expYear" />
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#paymentForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            expMonth: {
                validators: {
                    notEmpty: {
                        message: 'The expiration month is required'
                    },
                    digits: {
                        message: 'The expiration month can contain digits only'
                    },
                    callback: {
                        message: 'Expired',
                        callback: function(value, validator) {
                            value = parseInt(value, 10);
                            var year         = validator.getFieldElements('expYear').val(),
                                currentMonth = new Date().getMonth() + 1,
                                currentYear  = new Date().getFullYear();
                            if (value < 0 || value > 12) {
                                return false;
                            }
                            if (year == '') {
                                return true;
                            }
                            year = parseInt(year, 10);
                            if (year > currentYear || (year == currentYear && value > currentMonth)) {
                                validator.updateStatus('expYear', 'VALID');
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
                }
            },
            expYear: {
                validators: {
                    notEmpty: {
                        message: 'The expiration year is required'
                    },
                    digits: {
                        message: 'The expiration year can contain digits only'
                    },
                    callback: {
                        message: 'Expired',
                        callback: function(value, validator) {
                            value = parseInt(value, 10);
                            var month        = validator.getFieldElements('expMonth').val(),
                                currentMonth = new Date().getMonth() + 1,
                                currentYear  = new Date().getFullYear();
                            if (value < currentYear || value > currentYear + 10) {
                                return false;
                            }
                            if (month == '') {
                                return false;
                            }
                            month = parseInt(month, 10);
                            if (value > currentYear || (value == currentYear && month > currentMonth)) {
                                validator.updateStatus('expMonth', 'VALID');
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
                }
            }
        }
    });
});

validate

validate(): BootstrapValidator — Validate form manually. It is useful when you want to validate form by clicking a button or a link instead of a submit buttons.

$(form).bootstrapValidator(options).bootstrapValidator('validate');

// or
$(form).bootstrapValidator(options);
$(form).data('bootstrapValidator').validate();

validateField

validateField(field*): BootstrapValidator — Validate given field.

Parameter Type Description
field String|jQuery The field name or field element