1

我在表单中使用BootstrapValidation并且只有在填写另一个字段时才希望进行一些验证。

例如,我有这个表格:

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

我想检查是否只有在有名字的情况下才填写年龄。

有解决办法吗?

4

1 回答 1

3

可能是这样的:

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

});
于 2014-10-22T14:37:33.497 回答