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);
});
})
使用jQuery驗證插件https://jqueryvalidation.org/ –
可能的重複http://stackoverflow.com/questions/30644606/an-invalid-form-control-with-name-is-not-focusable- without-any-required-or-h –
@AneesSaban檢出鏈接,但這似乎與我的問題完全相關。我更願意進行適當的驗證,而不是依靠所需的屬性 –