如何阻止提交,直到使用jQuery Validate插件验证表单?

时间:2017-11-16 07:15:23

标签: jquery jquery-validate

我的表单上有一个搜索按钮,当我点击它时,onclick属性激活并跳转到我在onclick上提到的功能 这是我的按钮, <input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">

我希望当我点击搜索按钮第一次表单验证然后转到该功能但我不知道为什么在验证之前直接进入该功能

$('#myForm').validate({
    onclick:false,
        rules:{
                name:"required",
                dob:"required",
                email:{
                    required: true,
                    email: true
                },
                age:{
                    required: true,
                    number: true,
                    minlength:2,
                    maxlength:2
                }
              },
              messages:{
              name: "Please Enter Name",
              email: "Please Enter valid Email",
              number: "Please Enter Only Digits",
              min_length:"Please Enter Minimum 2 Digit",
              max_length:"Please Enter Maximum 2 Digit"
              }
        });

这是我的jquery验证码。

<form id="myForm" method="post">
                Name:<p><input id="name_search" class="form-control" type="text" name="name" placeholder="name" required></p>
                Date of Birth:<p><input class="form-control" id="dob_search" type="text" name="dob" placeholder="dd/mm/yy" required></p>
                Sex:<p> <select id="sex_search" name="sex" class="form-control">
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                            </select></p>
                Email:<p><input id="mail_search" type="email" class="form-control" name="email" placeholder="Enter your email" required></p>
                Age: <p><input id="age_search" class="form-control" type="text" name="age" placeholder="Age" required></p><br/>
                <input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search"></form>

这是我的表格

2 个答案:

答案 0 :(得分:1)

您的验证插件可能未加载。检查控制台是否有错误。

验证通过后也应调用getData('search')

中删除onclick="getData('search')"
<input style="float:right;" type="submit" onclick="getData('search')" id="search" class="btn btn-success" name="searchbtn" value="Search">

尝试添加

submitHandler: function(form) {
        getData('search');
      }:

in:

$("#myform").validate({
  submitHandler: function(form) {
    getData('search');
  }
});

答案 1 :(得分:0)

从html标记中删除onclick属性并在确认表单的有效性之后调用该函数,例如:

$('#myForm').validate({
    ....
});

$('#search').click(function() {
    //check if form is valid
    if ( $('#myform').valid() ) {
        //call the function
        getData('search');
    }
});