使用下面的代码,我正在验证客户端验证上的注册表单,并使用 post 方法将表单提交到我的 php 页面,并返回一个 json 对象供我的 jquery 处理。如您所见,我已经为初始验证设置了一些规则和消息,以便在客户端处理。在 php 方面,我让它报告请求的状态、给用户的消息以及可能存在的任何错误。我想知道的是,如果出现错误,我应该如何处理它,并且我希望我的表单以与用户在被跳过的情况下应该看到的完全相同的方式将错误显示给用户。
我希望看到发生的情况是,因为我的 json 对象中存在示例错误消息,所以它看到它附加到相应的字段名称并以某种方式应用与消息相同的类。
我的输出数组如下所示:
{
"status":"error",
"message":"The following form did not validate successfully. Please fix the form errors and try again.",
"errors":
{
"username":"This username is already available",
"email_address":"This email address is already available"
}
}
jQuery 验证
$.validator.setDefaults(
{
submitHandler: function() { alert("submitted!"); },
showErrors: function(map, list)
{
this.currentElements.parents('label:first, div:first').find('.has-error').remove();
this.currentElements.parents('.form-group:first').removeClass('has-error');
$.each(list, function(index, error)
{
var ee = $(error.element);
var eep = ee.parents('label:first').length ? ee.parents('label:first') : ee.parents('div:first');
ee.parents('.form-group:first').addClass('has-error');
eep.find('.has-error').remove();
eep.append('<p class="has-error help-block">' + error.message + '</p>');
});
}
});
$(function()
{
$("#register_form").validate({
rules: {
username: {
required: true,
},
password: {
required: true,
minlength: 6,
maxlength: 12
},
email_address: {
required: true,
email: true
},
},
messages: {
username: {
required: "Please enter a username",
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long",
maxlength: "Your password must be no more than 12 characters long"
},
email_address: {
required: "Please provide an email address",
email: "Please enter a valid email address"
}
},
submitHandler: function(form) {
var uri = "/register/process";
$.post(uri, $( "#register_form" ).serialize(), function(output)
{
if (output.status == "notice")
{
/*
notyfy({
text: output.message,
type: 'alert',
layout: 'center',
closeWith: ['click']
});
*/
}
else if(output.status == "error")
{
// Show errors even if jQuery validation missed some from server side validation.
notyfy({
text: output.message,
type: 'error',
layout: 'center',
closeWith: ['click']
});
}
else if(output.status == "success")
{
// Works
notyfy({
text: output.message,
type: 'success',
layout: 'center',
closeWith: ['click']
});
}
else
{
/*
notyfy({
text: output.message,
type: 'warning',
layout: 'center',
closeWith: ['click']
});
*/
}
}, 'json');
return false;
}
});
});
我一直试图从 jquery 验证插件的文档中了解要做什么,并认为我忽略了一些东西。有人知道或有什么建议吗?任何意见都将被接受。