jquery中validate与form插件提交的方式小结

概述:本篇主要讨论jquery.validate结合jquery.form实现对表单的验证和提交方案。

方式一:是通过jquery.validate的submitHandler选项,即当表单通过验证时执行回调函数在这个回调函数中通过jquery.form来提交表单;

方式二:是通过jquery.form的beforeSubmit,即在提交表单前执行的回调函数,这个函数如果返回true,则提交表单,如果返回false,则终止提交表单。根据jquery.validate插件的valid()方法,就可以通过jquery.form提交表单时来对表单进行验证。

方式三:是通过jquery.validate验证表单的validate方法。这个方法的好处是对表单验证的控制更加自由

实例:下面通过三个实例分别阐述上面的三种方式

载入CSS样式文件

代码如下:

CSS样式文件内容

<div class="jb51code">
<pre class="brush:css;">
input{
height:25px;
line-height:25px;
padding-left:4px;
}

span.checked{
padding: 0px 5px 0px 25px;
margin-left: 10px;
margin-top: 0px;
margin-bottom: 3px;
height: 25px;
line-height:25px;
font-size: 12px;
white-space: Nowrap;
text-align: left;
color: #E6594E;
background: url("images/acion2.png") no-repeat 3px; / #FCEAE8 /
}
span.unchecked{
padding: 0px 5px 0px 25px;
margin-left: 10px;
margin-top: 0px;
margin-bottom: 3px;
height: 23px;
line-height:23px;
font-size: 12px;
border: 1px solid #E6594E;
white-space: Nowrap;
text-align: left;
color: #E6594E;
background: #FCEAE8 url("images/acion.png") no-repeat 3px;
}

载入javascript文件

rush:xhtml;">

HTML内容

<div class="jb51code">
<pre class="brush:xhtml;">

jquery.validate+jquery.form提交的三种方式

*

*

jquery.validate+jquery.form提交方式1的javascript内容

<div class="jb51code">
<pre class="brush:js;">
<script language="javascript">
function showResponse(responseText,statusText) {
if(statusText=='success'){
$("#result").html(responseText);
}
}

$(document).ready(function(){
$('#commentForm').validate({
focusCleanup:true,focusInvalid:false,errorClass: "unchecked",validClass: "checked",errorElement: "span",submitHandler:function(form){
$(form).ajaxSubmit({
type:"post",url:"test_save.PHP?time="+ (new Date()).getTime(),//beforeSubmit: showRequest,success: showResponse
});
},errorPlacement:function(error,element){
var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']");
if(s!=null){
s.remove();
}
error.appendTo(element.parent());
},success: function(label) {
//label.addClass("valid").text("Ok!")
label.removeClass("unchecked").addClass("checked");
},rules:{
username:{required:true,minlength:3},email:{
required:true
}
}
});
});

jquery.validate+jquery.form提交方式2的javascript内容

<div class="jb51code">
<pre class="brush:js;">
<script language="javascript">
function showResponse(responseText,statusText) {
if(statusText=='success'){
$("#result").html(responseText);
}
}

function showRequest(formData,jqForm,options){
return $("#commentForm").valid();
}

$(document).ready(function(){
$('#commentForm').submit(function(){
$(this).ajaxSubmit({
type:"post",beforeSubmit:showRequest,success:showResponse
});
return false; //此处必须返回false,阻止常规的form提交
});

$('#commentForm').validate({
focusCleanup:true,email:{
required:true
}
}
});
});

jquery.validate+jquery.form提交方式3的javascript内容

<div class="jb51code">
<pre class="brush:js;">
<script language="javascript">
var options={
focusCleanup:true,email:{
required:true
}
}
};

function showResponse(responseText,options){
return $("#commentForm").valid();
}

$(document).ready(function(){
validator=$('#commentForm').validate(options);
$("#reset").click(function(){
validator.resetForm();
});

$("button").click(function(){
validator.form();
});

$('#commentForm').submit(function(){
$(this).ajaxSubmit({
type:"post",success:showResponse
});
return false; //此处必须返回false,阻止常规的form提交
});
});

DEMO源码:

一些问题

1、其实这个问题在昨天晚上写这篇文章的时候就有发现,即我在HTML文件头使用时,输入框及错误信息的样式似乎有些问题。不过今天发现问题并非这么简单,在使用时,针对“姓名”这个输入框来说——只须达到三个字符就认为通过验证——在输入第一个字符、第二个字符时,错误显示正常,输入第三个字符时,错误显示消失,并显示一个表示验证通过的“逗号”图片。到目前为止,一切似乎都很正常,但如果在继续输入字符,比如输入第四个字符、第五个字符......问题出现了。如下图所示:

不使用,而使用时没有这样的问题,一切正常。不过,现在的问题是,为什么加上会产生这样的问题?而且,做为前端来说,加上是必须的。

这个问题处理的比较纠结,这里罗列一下处理的过程。并且在最后给一个解决方

首先,是因为昨天在查看错误提示信息,关注一下插入错误信息的代码。我在errorPlacement中增加了一句:alert(element.parent().html());

<div class="jb51code">
<pre class="brush:js;">
errorPlacement:function(error,element){
alert(element.parent().html());
var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']");
if(s!=null){
s.remove();
}
error.appendTo(element.parent());
},

输入第一个字符时,得到如下图所示

输入三个字符,验证成功后,得到如下图所示:

继续输入更多字符,得到如下图所示

这就说明了以下几个问题:

1、不管验证失败还是成功,都会调用errorPlacement:function(...)

2、s.remove()没有起作用。

由于在写这篇文章时使用的是而不是,弹出的内容是htmlFor="cusername",而不是for="cusername",如下图所示:

因此,上面的代码中写成如下的方式

rush:js;"> var s=element.parent().find("span[htmlFor='" + element.attr("id") + "']"); if(s!=null){ s.remove(); }

然而在下,无法根据htmlFor找到,因此这里应该把htmlFor改成for,即

<div class="jb51code">
<pre class="brush:js;">
errorPlacement:function(error,element){
alert(element.parent().html());
var s=element.parent().find("span[for='" + element.attr("id") + "']");
if(s!=null){
s.remove();
}
error.appendTo(element.parent());
},

问题似乎解决了。但上面提到,不管验证成功或失败,都会调用errorPlacement:function(...),那可以在这里判断有没有错误,如果有错误,则显示。防止已经验证成功的情况下仍会调用。这样就不会寻找span的for属性值是否为当前控件的name名称了(例子中是for="cusername")。改进的代码如下:

rush:js;"> errorPlacement:function(error,element){ if(error.html()!=''){ error.appendTo(element.parent()); } },

虽然解决问题,但是在chrome、firefox下仍有问题。了解这个问题的现象,可以用firefox或chrome测试一下——焦点离开输入框后,无法验证,只有点击“提交”按钮后才可以验证——这个问题的解决方案目前还没有深入下去。但是有解决的办法是,将上面的jquery1.6.2换成jquery1.3.2或jquery1.4(其它的jquery版本未测试,可能是低于jquery1.6.2的版本都可以)即可解决这个问题。

建议:

1、使用jquery1.3.2版本,这样可以节省很多时间来解决兼容方面的问题。

更多:

本例子中的jquery.validate,解决了remote远程验证只返回true or false的局限。可以返回代码及出错的提示信息,更好的人性化需求。使用方法在这介绍一下

增加以下函数

<div class="jb51code">
<pre class="brush:js;">
function GetRemoteInfo(postUrl,data){
var remote = {
type: "POST",async: false,url: postUrl,dataType: "xml",data: data,dataFilter: function(dataxML) {
var result = new Object();
result.Result = jQuery(dataxML).find("Result").text();
result.Msg = jQuery(dataxML).find("Msg").text();
//alert(result.Result);
if (result.Result == "-1") {
result.Result = false;
return result;
}else{
result.Result = result.Result == "1" ? true : false;
return result;
}
}
};
return remote;
}

<div class="jb51code">
<pre class="brush:js;">
$(document).ready(function(){
var dataInfo ={email:function(){return $("#cemail").val();}};
var remoteInfo = GetRemoteInfo('check-email.PHP?time='+(new Date()).getTime(),dataInfo);
$('#commentForm').validate({
rules:{
username:{
required:true,minlength:3
},email:{
required:true,remote:remoteInfo
}
}
});
....
});

check-email.PHP返回的内容为xml格式,格式如下

<div class="jb51code">
<pre class="brush:js;">
<?PHP
header("Content-Type:text/xml");
echo '<?'.'xml version="1.0" encoding="utf-8"'.' ?>';
?>

用户名格式不正确,用户名必须包含testa,请重新输入! 0

result值为0,返回的是false,表示验证失败;result值为1,返回的是true,表示验证成功

jquery.formjquery.validate

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...