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?

0

1 Answer 1

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

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.