jQuery 即使发生验证错误,验证插件也会提交

jQuery validation plugin submits even if validation errors occur

我正在尝试使用 jQuery 验证 bootstrap 表单。

  var formSubmit =  $("#dl-mg-form-publish").validate({
        rules: {
            'dl-mg-input-youtube': {
                required: true,
                url:true,
            },
            'dl-mg-input-title': {
                required: true,
                minlength: 6   });

我正在尝试验证这一点:

 var videoInformation = {
        youtubeID: $('#dl-mg-input-youtube').val(),
        title: $('#dl-mg-input-title').val(), }

这是我的html:

  <form class="form-horizontal dl-mg-form-horizontal" id="dl-mg-form-publish"  action="#">


    <div class="form-group">
        <label for="dl-mg-input-youtube" class="control-label col-xs-2">YouTube Video ID:</label>

        <div class="col-xs-6">
            <input type="url" class="form-control" id="dl-mg-input-youtube" name="dl-mg-input-youtube" placeholder="Youtube ID">

        </div>

    </div>

    <div class="form-group">
        <label for="dl-mg-input-title" class="control-label col-xs-2">Video Title:</label>

        <div class="col-xs-6">
            <input type="text" class="form-control" id="dl-mg-input-title" name="dl-mg-input-title" placeholder="Video Title">

        </div>
    </div>

我是编程新手,我不知道如何先验证然后提交。我尝试使用 .click 处理程序,但它无论如何都会提交有错误的字段。请帮忙!

在提交表单之前,您需要验证表单。您可以在 click 事件中执行此操作,例如:

$("#target").click(function () {

    // Validate the form first
    if (!$("#dl-mg-form-publish").valid()) return false;

    // Your form is valid, so continue with you submit logic..
});

更多信息在这里:.valid()

编辑:

禁用按键自动验证

将此选项用于 validate() 方法:

$("#dl-mg-form-publish").validate({
     onfocusout: false,
     onkeyup: false,
     // other options here
})