如何使用Bootstrap验证提交表单

时间:2016-03-29 13:10:52

标签: jquery forms bootstrapvalidator

我正在使用Bootstrapvalidation来检查我的输入字段。最重要的是,我在提交时进行了额外的检查。它提交时没有显示错误,或者当我使用它时:

$("#form").submit(function(ev){
    ev.preventDefault();
});

$("#submit-form").on("click", function(){
    var valid=some code for additional check;
    if (valid) {
        $("#form").submit();
    }
    else {
        return;
    }
});

但是它只是递归而且表单没有提交。如何让这个工作?

2 个答案:

答案 0 :(得分:1)

参考以下示例

<script>
$(document).ready(function() {
    $('#taskForm')
        .formValidation({
            framework: 'bootstrap',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                task: {
                    validators: {
                        notEmpty: {
                            message: 'The task is required'
                        }
                    }
                },
                description: {
                    validators: {
                        notEmpty: {
                            message: 'The description is required'
                        }
                    }
                }
            }
        })
        .on('success.field.fv', function(e, data) {
            if (data.fv.getInvalidFields().length > 0) {    // There is invalid field
                data.fv.disableSubmitButtons(true);
            }
        });
});
</script>
<form id="taskForm" method="post" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Task</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="task" />
        </div>
    </div>

    <div class="form-group">
        <label class="col-xs-3 control-label">Description</label>
        <div class="col-xs-5">
            <textarea class="form-control" name="description" rows="5"></textarea>
        </div>
    </div>

    <div class="form-group">
        <div class="col-xs-5 col-xs-offset-3">
            <!-- Initially, the submit button is disabled -->
            <button type="submit" class="btn btn-default" disabled="disabled">Submit</button>
        </div>
    </div>
</form>

答案 1 :(得分:1)

@ Harshil的答案涵盖了bootstrapValidation插件,这是一个完全不同的插件然后1000hz BootstrapValidator插件

在您的方法中,您在第一个脚本中有ev.preventDefault();这是单独的脚本并且阻止表单提交无关紧要输入字段/附加检查是有效还是无效且输入状态/附加检查有效或在第一个脚本中根本没有定义无效。

您需要Conditionally handling the submit event来检查和处理additional custom check以及其他表单输入字段以进行验证,如果一切正常,请提交表单,

$('#form').validator().on('submit', function (e) {
  if (e.isDefaultPrevented()) {
    // handle the invalid form...
  } else {
    // everything looks good!
  }
})