Ajax 请求前的 Jquery 表单验证

Vip*_*ngh 1 javascript ajax jquery

我已经浏览了其他线程并使用了一个作为参考,但仍然无法找到解决方案。
我的问题是:

我正在按钮单击时调用一个函数,该函数在验证后已验证我试图在提交处理程序中使用 ajax 请求发布数据,问题是我的字段正在得到验证,但未调用 Ajax 请求。

<input type="button" value="Register" id="registerP" onclick="registerPatient()"  class="form-control input-sm btn-success ">

function registerPatient(){
$("#patientRegistration").validate({
rules: {
    patientName: {
    required: true,
    textOnly: true
                },
       },
messages: {
       patientName: {
       required: "Please enter the full name",                  
                    },
          },
submitHandler: function(form) { 
            $.ajax({
             type: "POST",
             url: "/LoginMavenSpringMVC/appointment/savePatient",
             data: "patientName=" + patientName,
         success: function(response){},
         error: function(e){}
      });
  }
 });
}  
Run Code Online (Sandbox Code Playgroud)

但是,如果我不使用验证并直接调用 Ajax,我就可以发布数据。请建议我要去哪里错了。

Bha*_*mar 5

您可以尝试这样调用 jquery 表单验证并检查是否已验证:

$(document).ready(function(){
  $("#patientRegistration").validate({
    rules: {
        patientName: {
        required: true,
        textOnly: true
                    },
           },
    messages: {
           patientName: {
           required: "Please enter the full name",                  
                        },
              }
     });
});

function registerPatient(){
   var IsValid=$("#patientRegistration").valid();
   if(IsValid){
     var patientName=""; //value for patient name
     $.ajax({
             type: "POST",
             url: "/LoginMavenSpringMVC/appointment/savePatient",
             data: {"patientName": patientName},
             success: function(response){},
             error: function(e){}
     });
   }
}
Run Code Online (Sandbox Code Playgroud)