Dougui
Dougui

Reputation: 7232

Conditional validation with BootstrapValidation

I am using BootstrapValidation in a form and I want to have some validations only if another field is filled.

For example, I have this form :

<form>
  <input type="text" name="name"/>
  <input type="text" name="age"/>
</form>

I want to check if the age is filled only if there is name.

Is there a solution?

Upvotes: 1

Views: 3808

Answers (1)

karlingen
karlingen

Reputation: 14625

Something like this perhaps:

$(document).ready(function() {
    $('form')
        .bootstrapValidator({
            fields: {
                name: {
                    enabled: false,
                    validators: {
                        notEmpty: {
                            message: 'The name is required and cannot be empty'
                        }
                    }
                },
                age: {
                    enabled: false,
                    validators: {
                        notEmpty: {
                            message: 'Age is required if name is set'
                        }
                    }
                }
            }
        })

        .on('keyup', '[name="name"]', function() {
            var isEmpty = $(this).val() == '';
            $('form')
                    .bootstrapValidator('enableFieldValidators', 'name', !isEmpty)
                    .bootstrapValidator('enableFieldValidators', 'age', !isEmpty);

            // Revalidate the field when user start typing in the name field
            if ($(this).val().length == 1) {
                $('form').bootstrapValidator('validateField', 'name')
                                .bootstrapValidator('validateField', 'age');
            }
        });

});

Upvotes: 3

Related Questions