【发布时间】:2016-07-06 07:41:32
【问题描述】:
我有一个使用 Ajax 设置为 POST 的表单。目前我的验证基本上是这个功能:
// Function for making all fields required
$(function(){
$("input").prop('required',true);
});
这很好用,但是由于我的部分表单使用 CSS 隐藏,具体取决于先前选择的答案 - 我在控制台中的所有隐藏字段中都收到以下错误:
An invalid form control with name='providerName' is not focusable.
有没有一种更简单的方法可以向 Ajax 表单添加验证,或许还有更多控制权?
例如某些字段需要链接 - 我想我可以验证输入是否具有“链接结构”
我的 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验证插件jqueryvalidation.org
-
@AneesSaban 查看了链接,但似乎与我的问题并不完全相关。我对进行适当的验证比依赖所需的属性更感兴趣
标签: javascript php jquery ajax validation