2016-07-06 95 views
0

我使用Ajax将表单设置为POST。目前我的验证基本上是这样的功能:使用Ajax POST进行验证

// Function for making all fields required 
$(function(){ 
    $("input").prop('required',true); 
}); 

这工作得很好,但是因为我的表单的部分使用依赖于以前的答案CSS选择隐藏 - 我收到以下错误控制台中的所有隐藏的字段:

​​

有没有一种更简单的方法来添加验证到Ajax表单,也许有更多的控制?

E.g.某些字段需要一个链接 - 我想我可以验证输入具有“连接结构”

我的Ajax POST代码示例:

// Wait for the DOM to be loaded 
$(document).ready(function() { 

    // Make sure New Provider is unchecked by default 
    document.getElementById("typeNew").checked = false; 

    // Variable to hold request 
    var request; 

    // Bind function to form submit event 
    $("#createPanelForm").submit(function(event){ 

     // Abort any pending request 
     if (request) { 
      request.abort(); 
     } 

     // Setup local variable 
     var $form = $(this); 

     // Select and cache form fields 
     var $inputs = $form.find("projectName, projectLink, type, providerName, completeLink, quotaFullLink, screenoutLink, existingProvider"); 

     // Serialize the data in the form 
     var serializedData = $form.serialize(); 

     // Disable the inputs for the duration of the Ajax request 
     // Disabled form inputs will not be serialized. 
     $inputs.prop("disabled", true); 

     // Send the request 
     request = $.post({ 
      url: "actions/createpanel.action.php", 
      method: "POST", 
      data: serializedData, 
      function(result){ 
       alert(result); 
      } 
     }); 

     // Callback handler for successful request 
     request.done(function (response, textStatus, jqXHR){ 
      // Log data to console 
      console.log(serializedData); 
      console.log(response); 
      document.getElementById('submitSuccess').style.display = 'block'; 
     }); 

     // Callback handler for failed request 
     request.fail(function (jqXHR, textStatus, errorThrown){ 
      // Log the error to console 
      console.error("Error: "+textStatus, errorThrown); 
      document.getElementById('submitError').style.display = 'block'; 
     }); 

     // Callback handler for both outcomes 
     request.always(function() { 
      // Reenable the inputs 
      $inputs.prop("disabled", false); 
     }); 

     // Prevent default form posting 
     event.preventDefault(); 

     // Hide form and show response 
     $("#createPanelForm").fadeOut(1000); 
     $("#submitResponse").delay(1001).fadeIn(1000);  
    }); 

}) 
+0

使用jQuery验证插件https://jqueryvalidation.org/ –

+1

可能的重复http://stackoverflow.com/questions/30644606/an-invalid-form-control-with-name-is-not-focusable- without-any-required-or-h –

+0

@AneesSaban检出链接,但这似乎与我的问题完全相关。我更愿意进行适当的验证,而不是依靠所需的属性 –

回答

0

添加novalidate属性表单会有所帮助:

<form name="myform" novalidate> 
+1

如果您可以发布某种示例或代码段,那将会更好。或者这也可以是评论。 –