programer.tips, another cool thing from @nghuuphuoc!

callback validator

Return the validity from a callback method

Validators

Improve it on Github

Options

Option HTML attribute Type Description
callback* data-bv-callback-callback Function The callback method
message data-bv-callback-message String The error message
When setting options via HTML attributes, remember to enable the validator by setting data-bv-callback="true".

The callback method must follow the format below:

function(value, validator, $field) {
    // value is the value of field
    // validator is instance of BootstrapValidator
    // $field is the jQuery object representing the field element

    // Check the field validity
    return true;    // or false
}

If you want to return a dynamic message, the callback function must return an object containing the valid and message members:

function(value, validator, $field) {
    // ... Do your logic checking
    if (...) {
        return {
            valid: true,    // or false
            message: 'The error message'
        }
    }

    return {
        valid: false,       // or true
        message: 'Other error message'
    }
}

Look at the dynamic message example.

Example

Basic example

In the following form, user is asked to enter a correct answer of simple operation which is generated randomly.

The captcha is also generated after form submission by triggering the error.form.bv event.

<form id="captchaForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-3 control-label" id="captchaOperation"></label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="captcha" />
        </div>
    </div>

    <div class="form-group">
        <div class="col-sm-5 col-sm-offset-3">
            <button type="submit" class="btn btn-default">Validate</button>
        </div>
    </div>
</form>
$(document).ready(function() {
    function randomNumber(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    };

    function generateCaptcha() {
        $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
    };

    generateCaptcha();

    $('#captchaForm')
        .bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                captcha: {
                    validators: {
                        callback: {
                            message: 'Wrong answer',
                            callback: function (value, validator, $field) {
                                // Determine the numbers which are generated in captchaOperation
                                var items = $('#captchaOperation').html().split(' '),
                                    sum   = parseInt(items[0]) + parseInt(items[2]);
                                return value == sum;
                            }
                        }
                    }
                }
            }
        })
        .on('error.form.bv', function (e) {
            generateCaptcha();
        });
});

It's possible to use HTML 5 attributes to set the callback as following snippet:

<form id="callbackForm" class="form-horizontal"
    data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
    data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
    data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">

    <div class="form-group">
        <label class="col-lg-3 control-label" id="captchaOperation"></label>
        <div class="col-lg-2">
            <input type="text" class="form-control" name="captcha"
                data-bv-callback="true"
                data-bv-callback-message="Wrong answer"
                data-bv-callback-callback="checkCaptcha" />
        </div>
    </div>
</form>
// IMPORTANT NOTICE: You have to declare the callback as a global function
// outside of $(document).ready()
function checkCaptcha(value, validator) {
    // Determine the numbers which are generated in captchaOperation
    var items = $('#captchaOperation').html().split(' '),
        sum   = parseInt(items[0]) + parseInt(items[2]);
    return value == sum;
};

$(document).ready(function() {
    // Return a random number between min and max
    function randomNumber(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    };

    // Generate a sum of two random numbers
    function generateCaptcha() {
        $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
    };

    generateCaptcha();

    $('#callbackForm').bootstrapValidator();
});

Dynamic message example

The form below ask to enter a secure password, which must satisfies all the following conditions:

  • Must be more than 8 characters long
  • Must contain at least one upper case character
  • Must contain at least one lower case character
  • Must contain at least one digit
<form id="securePasswordForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-3 control-label">Password</label>
        <div class="col-sm-5">
            <input type="password" class="form-control" name="pwd" />
        </div>
    </div>
</form>
$(document).ready(function() {
    $('#securePasswordForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            pwd: {
                validators: {
                    notEmpty: {
                        message: 'The password is required and cannot be empty'
                    },
                    callback: {
                        message: 'The password is not valid',
                        callback: function(value, validator, $field) {
                            if (value === '') {
                                return true;
                            }

                            // Check the password strength
                            if (value.length < 8) {
                                return {
                                    valid: false,
                                    message: 'It must be more than 8 characters long'
                                };
                            }

                            // The password doesn't contain any uppercase character
                            if (value === value.toLowerCase()) {
                                return {
                                    valid: false,
                                    message: 'It must contain at least one upper case character'
                                }
                            }

                            // The password doesn't contain any uppercase character
                            if (value === value.toUpperCase()) {
                                return {
                                    valid: false,
                                    message: 'It must contain at least one lower case character'
                                }
                            }

                            // The password doesn't contain any digit
                            if (value.search(/[0-9]/) < 0) {
                                return {
                                    valid: false,
                                    message: 'It must contain at least one digit'
                                }
                            }

                            return true;
                        }
                    }
                }
            }
        }
    });
});