使用BootstrapValidation进行条件验证



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

例如,我有这样的表格:

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

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

有解决方案吗?

可能是这样的:

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

最新更新