1

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?

Dougui
  • 7,142
  • 7
  • 52
  • 87

1 Answers1

3

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');
            }
        });

});
karlingen
  • 13,800
  • 5
  • 43
  • 74