Ajax 提交前的 jQuery 表单验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11469616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:38:20  来源:igfitidea点击:

jQuery Form Validation before Ajax submit

jqueryajaxjquery-validatevalidation

提问by Tom

JavaScript bit:

JavaScript 位:

$(document).ready(function()
    {
            $('#form').submit(function(e)
            {     

                e.preventDefault();
                var $form = $(this);

                // check if the input is valid
                if(! $form.valid()) return false;
                    $.ajax(
                    {
                    type:'POST',
                    url:'add.php',
                    data:$('#form').serialize(),
                    success:function(response)
                    {
                        $("#answers").html(response);
                    }
                });     

            })
    });

HTML bit:

HTML位:

    <input type="text" name="answer[1]" class="required" />
    <input type="text" name="answer[2]" class="required" />

So this is the code I am trying to use. The idea is to get all my inputs validated before I send my form with Ajax. I've tried numerous versions of this now but every time I end up with submitting even though the form is not entirely filled out. All my inputs are of the "required" class. Can anyone see what I am doing wrong?

所以这是我尝试使用的代码。这个想法是在我使用 Ajax 发送表单之前验证我的所有输入。我现在已经尝试了很多版本,但每次我最终都会提交,即使表格没有完全填写。我所有的输入都是“必需的”类。谁能看到我做错了什么?

Also, I depend on class-based requirements as my input names are generated with php so I can never be sure what name[id] or input types I get.

此外,我依赖于基于类的要求,因为我的输入名称是用 php 生成的,所以我永远无法确定我得到的是什么名称 [id] 或输入类型。

I show/hide questions as I go through it in "pages".

我在“页面”中浏览时显示/隐藏问题。

<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>

JS:

JS:

function toggleVisibility(newSection) 
        {
            $(".section").not("#" + newSection).hide();
            $("#" + newSection).show();
        } 

回答by Darin Dimitrov

You could use the submitHandleroption. Basically put the $.ajaxcall inside this handler, i.e. invert it with the validation setup logic.

您可以使用该submitHandler选项。基本上把$.ajax调用放在这个处理程序中,即用验证设置逻辑反转它。

$('#form').validate({

    ... your validation rules come here,

    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {
                $('#answers').html(response);
            }            
        });
    }
});

The jQuery.validateplugin will invoke the submit handler if the validation has passed.

jQuery.validate如果验证通过,插件将调用提交处理程序。

回答by amd

first you don't need to add the classRulesexplicitly since requiredis automatically detected by the jquery.validate plugin. so you can use this code :

首先,您不需要classRules显式添加,因为requiredjquery.validate 插件会自动检测到它。所以你可以使用这个代码:

  1. on form submit , you prevent the default behavior
  2. if the form is Invalid stop the execution.
  3. else if valid send the ajax request.

    $('#form').submit(    function(e){     
    
                e.preventDefault();
                var $form = $(this);
    
              // check if the input is valid
                if(! $form.valid()) return false;
    
               $.ajax({
                    type: 'POST',
                    url: 'add.php',
                    data: $('#form').serialize(),
                    success: function(response) {
                        $("#answers").html(response);
                    }
    
                });
            });
    
  1. 在表单提交时,您可以防止默认行为
  2. 如果表单无效,则停止执行。
  3. 否则如果有效发送ajax请求。

    $('#form').submit(    function(e){     
    
                e.preventDefault();
                var $form = $(this);
    
              // check if the input is valid
                if(! $form.valid()) return false;
    
               $.ajax({
                    type: 'POST',
                    url: 'add.php',
                    data: $('#form').serialize(),
                    success: function(response) {
                        $("#answers").html(response);
                    }
    
                });
            });
    

回答by Erik Grosskurth

This specific example will just check for inputs but you could tweak it however, Add something like this to your .ajax function:

这个特定的例子只会检查输入,但你可以调整它,将这样的东西添加到你的 .ajax 函数中:

beforeSend: function() {                    
    $empty = $('form#yourForm').find("input").filter(function() {
        return this.value === "";
    });
    if($empty.length) {
        alert('You must fill out all fields in order to submit a change');
        return false;
    }else{
        return true;
    };
},

回答by Arkadiusz 'flies' Rzadkowolski

You can try doing:

你可以尝试这样做:

if($("#form").validate()) {
 return true;
} else {
 return false;
}

回答by user3655384

> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##

$("form#data").validate({
    rules: {
        first: {
                required: true,
            },
        middle: {
            required: true,
        },          
        image: {
            required: true,
        },
    },
    messages: {
        first: {
                required: "Please enter first",
            },
        middle: {
            required: "Please enter middle",
        },          
        image: {
            required: "Please Select logo",
        },
    },
    submitHandler: function(form) {
        var formData = new FormData($("#image")[0]);
        $(form).ajaxSubmit({
            url:"action.php",
            type:"post",
            success: function(data,status){
              alert(data);
            }
        });
    }
});

回答by shahzad jam

I think submitHandler with jquery validation is good solution. Please get idea from this code. Inspired from @Darin Dimitrov

我认为带有 jquery 验证的 submitHandler 是一个很好的解决方案。请从这段代码中得到想法。灵感来自@Darin Dimitrov

$('.calculate').validate({

                submitHandler: function(form) {
                    $.ajax({
                        url: 'response.php',
                        type: 'POST',
                        data: $(form).serialize(),
                        success: function(response) {
                            $('#'+form.id+' .ht-response-data').html(response);
                        }            
                    });
                }
            });

回答by Mantas Vaitkūnas

I think that i first validate form and if validation will pass, than i would make ajax post. Dont forget to add "return false" at the end of the script.

我认为我首先验证表单,如果验证通过,我会发布 ajax 帖子。不要忘记在脚本末尾添加“return false”。

回答by luis

function validateForm()
{
    var a=document.forms["Form"]["firstname"].value;
    var b=document.forms["Form"]["midname"].value;
    var c=document.forms["Form"]["lastname"].value;
    var d=document.forms["Form"]["tribe"].value;
    if (a==null || a=="",b==null || b=="",c==null || c=="",d==null || d=="")
    {
        alert("Please Fill All Required Field");
        return false;
    }
    else{

        $.ajax({
        type: 'post',
        url: 'add.php',
        data: $('form').serialize(),
        success: function () {
          alert('Patient added');
          document.getElementById("form").reset();
        }
      });

    }
}

  $(function () {

    $('form').on('submit', function (e) {
      e.preventDefault();

      validateForm();


    });
  });

回答by jforjs

Form native JavaScript checkValidityfunction is more then enough to trigger the HTML5validation

表单原生 JavaScriptcheckValidity函数足以触发HTML5验证

$(document).ready(function() {
    $('#urlSubmit').click(function() {
        if($('#urlForm')[0].checkValidity()) {
            alert("form submitting");
        }
    });
});