formvalidation的ajax验证

来源:互联网 发布:华为天气软件apk 编辑:程序博客网 时间:2024/05/16 15:03
 jQuery插件之表单验证插件validationEngine


普通验证的例子:http://www.position-relative.net/creation/formValidator/

ajax验证的例子:http://www.position-relative.net/creation/formValidator/demoSubmit.html

这个插件支持大部分的浏览器,但由于有使用到了css3的阴影和圆角样式,所以在IE浏览器下无法看到圆角和阴影效果(万恶的IE)。

插件包含三个文件:

jquery.validationEngine.js //插件主JS文件

jquery.validationEngine-cn.js //验证规则JS文件

validationEngine.jquery.css //样式表文件



使用方法:

( 1 ) 引入jquery和插件js、css文件

---------------------------------------------------------------------------------------------------------------------

<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />

<script src="js/jquery.js" type="text/javascript"></script>

<script src="js/jquery.validationEngine-cn" type="text/javascript"></script>

<script src="js/jquery.validationEngine.js" type="text/javascript"></script>

---------------------------------------------------------------------------------------------------------------------



( 2 ) 初始化插件

在页面head区域加入如下代码:

---------------------------------------------------------------------------------------------------------------------

$(document).ready(function() {

$("#formID").validationEngine() ; //formID是你要验证的表单ID

})

---------------------------------------------------------------------------------------------------------------------



( 3 ) 添加表单元素验证规则

验证规则写在表单元素的class属性内即可。如验证text文本框:

---------------------------------------------------------------------------------------------------------------------

<input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" />

---------------------------------------------------------------------------------------------------------------------

注:本例使用4个验证规则,各规则之间以“,”分隔。

required:不可为空

custom[noSpecialCaracters]:不能有特殊字符(这是一个自定义规则,自定义规则格式为custom[自定义规则名],其中自定义规则在jquery.validationEngine-cn文件中定义。

length[0,20]:长度必须在0-20位之间。

ajax[ajaxUser]:这是一个Ajax验证,后面详细说明。



( 4 ) 验证触发

你可以在点击提交按钮后才触发验证

---------------------------------------------------------------------------------------------------------------------

$("#formID").validationEngine({

inlineValidation: false, //在这里修改

success : false,

failure : function() { callFailFunction() }

})

---------------------------------------------------------------------------------------------------------------------



默认的是在鼠标失去焦点后才开始验证,也就是绑定的是blur事件,可修改。

---------------------------------------------------------------------------------------------------------------------

$("#formID").validationEngine({

validationEventTriggers:"keyup blur", //这里增加了个keyup,也就是键盘按键起来就触发验证

success : false,

failure : function() { callFailFunction() }

})

---------------------------------------------------------------------------------------------------------------------



( 5) 修改错误提示层位置

---------------------------------------------------------------------------------------------------------------------

$("#formID").validationEngine({

promptPosition: "topRight", // 有5种模式 topLeft, topRight, bottomLeft, centerRight, bottomRight

success : false,

failure : function() {

})

---------------------------------------------------------------------------------------------------------------------



( 6) Ajax验证

---------------------------------------------------------------------------------------------------------------------

<input name="login_name" type="text" class="validate[ajax[ajaxUser]] text" id="login_name" >

---------------------------------------------------------------------------------------------------------------------

此验证要实现:在文本框中输入用户名,文本框失去焦点时检测用户名是否已被注册,如果已被注册显示提示“用户名已被使用”,如果还没有被注册则显示提示“用户名可以使用”。



此处使用了验证规则ajax[ajaxUser] ,看看jquery.validationEngine-cn中验证规则定义:

---------------------------------------------------------------------------------------------------------------------

"ajaxUser":{

"file":"validateUser.asp" //后台脚本文件,插件会POST三个参数:validateError;validateId;validateValue,后台脚本直接 request即可

"alertTextOk":"* 用户名可以使用.",

"alertTextLoad":"* 检查中, 请稍后...",

"alertText":"* 用户名已被使用."

},

---------------------------------------------------------------------------------------------------------------------

说明:后台脚本文件必须返回json格式数据。

插件官方提供的示例为php脚本,代码如下:

---------------------------------------------------------------------------------------------------------------------

<?php

$validateValue=$_POST['validateValue']; //获取post参数:文本框值

$validateId=$_POST['validateId']; //获取post参数:文本框ID

$validateError=$_POST['validateError'];

$arrayToJs = array(); //定义json返回数组,顺序必须为validateId、validateError、returnValue

$arrayToJs[0] = $validateId;

$arrayToJs[1] = $validateError;

if($validateValue =="karnius"){ //如果输入值=karnius

$arrayToJs[2] = "true"; // 返回 TRUE

echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // 验证成功返回json数组

}else{

for($x=0;$x<1000000;$x++){

if($x == 990000){

$arrayToJs[2] = "false"; // 返回 TRUE

echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // 验证失败返回json数组

}

}

}

?>

---------------------------------------------------------------------------------------------------------------------

由于本人程序使用的是ASP,参考官方提供的php后台脚本编写ASP代码如下:

---------------------------------------------------------------------------------------------------------------------

<%

validateValue = request("validateValue")

validateId = request("validateId")

validateError = request("validateError")

sql="select * from Cms_Personnel where login_name='"&validateValue&"'"

dbCon.sqlStr = sql

set rs = dbCon.rsDB()

if not rs.eof then

response.Write("{'jsonValidateReturn':['"&validateId&"','"&validateError&"','false']}")

else

response.Write("{'jsonValidateReturn':['"&validateId&"','"&validateError&"','true']}")

end if

%>

---------------------------------------------------------------------------------------------------------------------

说明:php的json_encode(mixed $value )函数能对变量进行JSON 编码。

asp中只要Rsponse

{"jsonValidateReturn":["validateId","validateError","returnValue"]}

形式字串即可。

注意response的JSON数组元素顺序,必须是validateId、validateError、returnValue 。

---------------------------------------------------------------------------------------------------------------------

再附一段JAVA的Ajax后台脚本代码:

---------------------------------------------------------------------------------------------------------------------

public String vali() {

ActionContext ac = ActionContext.getContext();

HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

String validateId = request.getParameter("validateId"); //获取插件post参数validateId

logger.info("vali() - String validateId=" + validateId);

String validateValue = request.getParameter("validateValue"); //获取插件post参数validateValue

String validateError = request.getParameter("validateError"); //获取插件post参数validateError

logger.info("vali() - String validateError=" + validateError);

jsonValidateReturn.add(validateId);

jsonValidateReturn.add(validateError);

if(validateValue.equals("chen"))

jsonValidateReturn.add("true");

else

jsonValidateReturn.add("false");

return SUCCESS;

}

----------------------------------------
上面的java代码的ajax验证写的有些简单,不是很清楚。下面详细
介绍 struts2整合validationEngine的ajax的验证


jquery验证框架-form validation范例 收藏
formvalidator.html如下:

Java代码
1.<!DOCTYPE HTML PUBLIC "-//IETF//DTD LEVEL1//EN">  
2.<html>  
3.  <head>  
4.    <title>formvalidator.html</title>  
5.      
6.    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
7.    <meta http-equiv="description" content="this is my page">  
8.    <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
9.        <link rel="stylesheet" href="formValidator/css/validationEngine.jquery.css" type="text/css" />  
10.        <link rel="stylesheet" href="formValidator/css/template.css" type="text/css" />  
11.        <script src="formValidator/jquery.js" type="text/javascript"></script>  
12.        <script src="formValidator/js/jquery.validationEngine-cn.js" type="text/javascript"></script>  
13.        <script src="formValidator/js/jquery.validationEngine.js" type="text/javascript"></script>  
14. 
15. 
16.<script>    
17.        $(document).ready(function() {  
18.            $("#formID").validationEngine({  
19.            validationEventTriggers:"blur",  //触发的事件  validationEventTriggers:"keyup blur",  
20.            inlineValidation: true,//是否即时验证,false为提交表单时验证,默认true  
21.            success :  false,//为true时即使有不符合的也提交表单,false表示只有全部通过验证了才能提交表单,默认false  
22.            promptPosition: "topRight",//提示所在的位置,topLeft, topRight, bottomLeft,  centerRight, bottomRight  
23.            //failure : function() { alert("验证失败,请检查。");  }//验证失败时调用的函数  
24.            //success : function() { callSuccessFunction() },//验证通过时调用的函数  
25.            });  
26.        });  
27.    </script>   
28.  </head>  
29.    
30.  <body>  
31.    <form id="formID" class="formular" method="post" action="">  
32.            <fieldset>  
33.                <legend>User informations</legend>  
34.                <label>  
35.                    <span>Desired username (ajax validation, only karnius is available) : </span>  
36.                    <input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" />//ajax验证用户名的地方  
37.                </label>  
38.                <label>  
39.                    <span>First name (optional)</span>  
40.                    <input value="karnius"  class="validate[optional,custom[onlyLetter],length[0,100]] text-input" type="text" name="firstname" id="firstname" />  
41.                </label>  
42.                <label>  
43.                    <span>Last name : </span>  
44.                    <input value="karnius"  class="validate[required,custom[onlyLetter],length[0,100]] text-input" type="text" id="data[Use6][preferedColor]" name="lastname"  />  
45.                </label>  
46.                <div>  
47.                    <span>Radio Groupe : <br /></span>  
48.                    <span>radio 1: </span>  
49.                    <input class="validate[required] radio" type="radio" name="data[User][preferedColor]"  id="radio1"  value="5">  
50.                    <span>radio 2: </span>  
51.                    <input class="validate[required] radio" type="radio" name="data[User][preferedColor]"  id="radio2"  value="3"/>  
52.                    <span>radio 3: </span>  
53.                    <input class="validate[required] radio" type="radio" name="data[User][preferedColor]"  id="radio3"  value="9"/>  
54.                </div>  
55.                <div>  
56.                    <span>Minimum 2 checkbox : <br /></span>  
57.                  
58.                    <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox"  name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5">  
59.                    <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox"  name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5">  
60.                      
61.                    <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck2"  value="3"/>  
62.                  
63.                    <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck3"  value="9"/>  
64.                </div>  
65.                <label>  
66.                    <span>Date : (format YYYY-MM-DD)</span>  
67.                    <input value="1111-11-11"  class="validate[required,custom[date]] text-input" type="text" name="date"  id="date" />  
68.                </label>  
69.                <label>  
70.                    <span>Favorite sport 1:</span>  
71.                <select name="sport" id="sport"  class="validate[required]"  id="sport"  >  
72.                    <option value="">Choose a sport</option>  
73.                    <option value="option1">Tennis</option>  
74.                    <option value="option2">Football</option>  
75.                    <option value="option3">Golf</option>  
76.                </select>  
77.                </label>  
78.                <label>  
79.                    <span>Favorite sport 2:</span>  
80.                <select name="sport2" id="sport2" multiple class="validate[required]"  id="sport2"  >  
81.                    <option value="">Choose a sport</option>  
82.                    <option value="option1">Tennis</option>  
83.                    <option value="option2">Football</option>  
84.                    <option value="option3">Golf</option>  
85.                </select>  
86.                </label>  
87.                <label>  
88.                    <span>Age : </span>  
89.                    <input value="22"  class="validate[required,custom[onlyNumber],length[0,3]] text-input" type="text" name="age"  id="age" />  
90.                </label>  
91.                      
92.                <label>  
93.                    <span>Telephone : </span>  
94.                    <input value="1111111"  class="validate[required,custom[telephone]] text-input" type="text" name="telephone"  id="telephone" />  
95.                </label>  
96.                <label>  
97.                    <span>mobilephone : </span>  
98.                    <input value="111111"  class="validate[required,custom[mobilephone]] text-input" type="text" name="telphone"  id="telphone" />  
99.                </label>  
100.                <label>  
101.                    <span>chinese : </span>  
102.                    <input value="asdf"  class="validate[required,custom[chinese]] text-input" type="text" name="chinese"  id="chinese" />  
103.                </label>  
104.                <label>  
105.                    <span>url : </span>  
106.                    <input value="url"  class="validate[required,custom[url]] text-input" type="text" name="url"  id="url" />  
107.                </label>  
108.                <label>  
109.                    <span>zipcode : </span>  
110.                    <input value="zipcode"  class="validate[required,custom[zipcode]] text-input" type="text" name="zipcode"  id="zipcode" />  
111.                </label>  
112.                <label>  
113.                    <span>ip : </span>  
114.                    <input value="ip"  class="validate[required,custom[ip]] text-input" type="text" name="ip"  id="ip" />  
115.                </label>  
116.                <label>  
117.                    <span>qq : </span>  
118.                    <input value="01234"  class="validate[required,custom[qq]] text-input" type="text" name="qq"  id="qq" />  
119.                </label>  
120.            </fieldset>  
121.            <fieldset>  
122.                <legend>Password</legend>  
123.                <label>  
124.                    <span>Password : </span>  
125.                    <input value="karnius"  class="validate[required,length[6,11]] text-input" type="password" name="password"  id="password" />  
126.                </label>  
127.                <label>  
128.                    <span>Confirm password : </span>  
129.                    <input value="karnius"  class="validate[required,confirm[password]] text-input" type="password" name="password2"  id="password2" />  
130.                </label>  
131.            </fieldset>  
132.            <fieldset>  
133.                <legend>Email</legend>  
134.                <label>  
135.                    <span>Email address : </span>  
136.                    <input value="ced@hotmail.com"  class="validate[required,custom[email]] text-input" type="text" name="email" id="email"  />  
137.                </label>  
138.                <label>  
139.                    <span>Confirm email address : </span>  
140.                    <input value="ced@hotmail.com" class="validate[required,confirm[email]] text-input" type="text" name="email2"  id="email2" />  
141.                </label>  
142.            </fieldset>  
143.            <fieldset>  
144.                <legend>Comments</legend>  
145.                <label>  
146.                    <span>Comments : </span>  
147.                    <textarea value="ced@hotmail.com" class="validate[required,length[6,300]] text-input" name="comments" id="comments" /> </textarea>  
148.                </label>  
149. 
150.            </fieldset>  
151.            <fieldset>  
152.                <legend>Conditions</legend>  
153.                <div class="infos">Checking this box indicates that you accept terms of use. If you do not accept these terms, do not use this website : </div>  
154.                <label>  
155.                    <span class="checkbox">I accept terms of use : </span>  
156.                    <input class="validate[required] checkbox" type="checkbox"  id="agree"  name="agree"/>  
157.                </label>  
158.            </fieldset>  
159.<input class="submit" type="submit" value="Validate & Send the form!"/>  
160.<hr/>  
161.</form>  
162.  </body>  
163.</html> 
<!DOCTYPE HTML PUBLIC "-//IETF//DTD LEVEL1//EN">
<html>
  <head>
    <title>formvalidator.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="formValidator/css/validationEngine.jquery.css" type="text/css" />
<link rel="stylesheet" href="formValidator/css/template.css" type="text/css" />
<script src="formValidator/jquery.js" type="text/javascript"></script>
<script src="formValidator/js/jquery.validationEngine-cn.js" type="text/javascript"></script>
<script src="formValidator/js/jquery.validationEngine.js" type="text/javascript"></script>


<script>
$(document).ready(function() {
$("#formID").validationEngine({
validationEventTriggers:"blur",  //触发的事件  validationEventTriggers:"keyup blur",
inlineValidation: true,//是否即时验证,false为提交表单时验证,默认true
success :  false,//为true时即使有不符合的也提交表单,false表示只有全部通过验证了才能提交表单,默认false
promptPosition: "topRight",//提示所在的位置,topLeft, topRight, bottomLeft,  centerRight, bottomRight
//failure : function() { alert("验证失败,请检查。");  }//验证失败时调用的函数
//success : function() { callSuccessFunction() },//验证通过时调用的函数
});
});
</script>
  </head>
 
  <body>
    <form id="formID" class="formular" method="post" action="">
<fieldset>
<legend>User informations</legend>
<label>
<span>Desired username (ajax validation, only karnius is available) : </span>
<input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" />//ajax验证用户名的地方
</label>
<label>
<span>First name (optional)</span>
<input value="karnius"  class="validate[optional,custom[onlyLetter],length[0,100]] text-input" type="text" name="firstname" id="firstname" />
</label>
<label>
<span>Last name : </span>
<input value="karnius"  class="validate[required,custom[onlyLetter],length[0,100]] text-input" type="text" id="data[Use6][preferedColor]" name="lastname"  />
</label>
<div>
<span>Radio Groupe : <br /></span>
<span>radio 1: </span>
<input class="validate[required] radio" type="radio" name="data[User][preferedColor]"  id="radio1"  value="5">
<span>radio 2: </span>
<input class="validate[required] radio" type="radio" name="data[User][preferedColor]"  id="radio2"  value="3"/>
<span>radio 3: </span>
<input class="validate[required] radio" type="radio" name="data[User][preferedColor]"  id="radio3"  value="9"/>
</div>
<div>
<span>Minimum 2 checkbox : <br /></span>

<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox"  name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5">
<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox"  name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5">

<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck2"  value="3"/>

<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck3"  value="9"/>
</div>
<label>
<span>Date : (format YYYY-MM-DD)</span>
<input value="1111-11-11"  class="validate[required,custom[date]] text-input" type="text" name="date"  id="date" />
</label>
<label>
<span>Favorite sport 1:</span>
<select name="sport" id="sport"  class="validate[required]"  id="sport"  >
<option value="">Choose a sport</option>
<option value="option1">Tennis</option>
<option value="option2">Football</option>
<option value="option3">Golf</option>
</select>
</label>
<label>
<span>Favorite sport 2:</span>
<select name="sport2" id="sport2" multiple class="validate[required]"  id="sport2"  >
<option value="">Choose a sport</option>
<option value="option1">Tennis</option>
<option value="option2">Football</option>
<option value="option3">Golf</option>
</select>
</label>
<label>
<span>Age : </span>
<input value="22"  class="validate[required,custom[onlyNumber],length[0,3]] text-input" type="text" name="age"  id="age" />
</label>

<label>
<span>Telephone : </span>
<input value="1111111"  class="validate[required,custom[telephone]] text-input" type="text" name="telephone"  id="telephone" />
</label>
<label>
<span>mobilephone : </span>
<input value="111111"  class="validate[required,custom[mobilephone]] text-input" type="text" name="telphone"  id="telphone" />
</label>
<label>
<span>chinese : </span>
<input value="asdf"  class="validate[required,custom[chinese]] text-input" type="text" name="chinese"  id="chinese" />
</label>
<label>
<span>url : </span>
<input value="url"  class="validate[required,custom[url]] text-input" type="text" name="url"  id="url" />
</label>
<label>
<span>zipcode : </span>
<input value="zipcode"  class="validate[required,custom[zipcode]] text-input" type="text" name="zipcode"  id="zipcode" />
</label>
<label>
<span>ip : </span>
<input value="ip"  class="validate[required,custom[ip]] text-input" type="text" name="ip"  id="ip" />
</label>
<label>
<span>qq : </span>
<input value="01234"  class="validate[required,custom[qq]] text-input" type="text" name="qq"  id="qq" />
</label>
</fieldset>
<fieldset>
<legend>Password</legend>
<label>
<span>Password : </span>
<input value="karnius"  class="validate[required,length[6,11]] text-input" type="password" name="password"  id="password" />
</label>
<label>
<span>Confirm password : </span>
<input value="karnius"  class="validate[required,confirm[password]] text-input" type="password" name="password2"  id="password2" />
</label>
</fieldset>
<fieldset>
<legend>Email</legend>
<label>
<span>Email address : </span>
<input value="ced@hotmail.com"  class="validate[required,custom[email]] text-input" type="text" name="email" id="email"  />
</label>
<label>
<span>Confirm email address : </span>
<input value="ced@hotmail.com" class="validate[required,confirm[email]] text-input" type="text" name="email2"  id="email2" />
</label>
</fieldset>
<fieldset>
<legend>Comments</legend>
<label>
<span>Comments : </span>
<textarea value="ced@hotmail.com" class="validate[required,length[6,300]] text-input" name="comments" id="comments" /> </textarea>
</label>

</fieldset>
<fieldset>
<legend>Conditions</legend>
<div class="infos">Checking this box indicates that you accept terms of use. If you do not accept these terms, do not use this website : </div>
<label>
<span class="checkbox">I accept terms of use : </span>
<input class="validate[required] checkbox" type="checkbox"  id="agree"  name="agree"/>
</label>
</fieldset>
<input class="submit" type="submit" value="Validate & Send the form!"/>
<hr/>
</form>
  </body>
</html>



jquery.validationEngine-cn.js如下:

Java代码
1. 
2. 
3.(function($) {  
4.    $.fn.validationEngineLanguage = function() {};  
5.    $.validationEngineLanguage = {  
6.        newLang: function() {  
7.            $.validationEngineLanguage.allRules =   {"required":{               // Add your regex rules here, you can take telephone as an example  
8.                        "regex":"none",  
9.                        "alertText":"* 非空选项.",  
10.                        "alertTextCheckboxMultiple":"* 请选择一个单选框.",  
11.                        "alertTextCheckboxe":"* 请选择一个复选框."},  
12.                    "length":{  
13.                        "regex":"none",  
14.                        "alertText":"* 长度必须在 ",  
15.                        "alertText2":" 至 ",  
16.                        "alertText3": " 之间."},  
17.                    "maxCheckbox":{  
18.                        "regex":"none",  
19.                        "alertText":"* 最多选择 ",//官方文档这里有问题  
20.                        "alertText2":" 项."},      
21.                    "minCheckbox":{  
22.                        "regex":"none",  
23.                        "alertText":"* 至少选择 ",  
24.                        "alertText2":" 项."},      
25.                    "confirm":{  
26.                        "regex":"none",  
27.                        "alertText":"* 两次输入不一致,请重新输入."},          
28.                    "telephone":{  
29.                        "regex":"/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/",  
30.                        "alertText":"* 请输入有效的电话号码,如:010-29292929."},  
31.                    "mobilephone":{  
32.                        "regex":"/(^0?[1][358][0-9]{9}$)/",  
33.                        "alertText":"* 请输入有效的手机号码."},     
34.                    "email":{  
35.                        "regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",  
36.                        "alertText":"* 请输入有效的邮件地址."},     
37.                    "date":{  
38.                         "regex":"/^(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$/",  
39.                         "alertText":"* 请输入有效的日期,如:2008-08-08."},  
40.                    "ip":{  
41.                         "regex":"/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/",  
42.                         "alertText":"* 请输入有效的IP."},  
43.                    "chinese":{  
44.                        "regex":"/^[\u4e00-\u9fa5]+$/",  
45.                        "alertText":"* 请输入中文."},  
46.                    "url":{  
47.                        "regex":"/^[a-zA-z]:\\/\\/[^s]$/",//这些验证请自己加强  
48.                        "alertText":"* 请输入有效的网址."},  
49.                    "zipcode":{  
50.                        "regex":"/^[1-9]\d{5}$/",  
51.                        "alertText":"* 请输入有效的邮政编码."},  
52.                    "qq":{  
53.                        "regex":"/^[1-9]\d{4,9}$/",  
54.                        "alertText":"* 请输入有效的QQ号码."},  
55.                    "onlyNumber":{  
56.                        "regex":"/^[0-9]+$/",  
57.                        "alertText":"* 请输入数字."},  
58.                    "onlyLetter":{  
59.                        "regex":"/^[a-zA-Z]+$/",  
60.                        "alertText":"* 请输入英文字母."},  
61.                    "noSpecialCaracters":{  
62.                        "regex":"/^[0-9a-zA-Z]+$/",  
63.                        "alertText":"* 请输入英文字母和数字."},     
64.                    "ajaxUser":{  
65.                        "file":"validate.action",//ajax验证用户名,会post如下参数:validateError    ajaxUser;validateId user;validateValue  cccc  
66.                        "alertTextOk":"* 帐号可以使用.",    
67.                        "alertTextLoad":"* 检查中, 请稍后...",  
68.                        "alertText":"* 帐号不能使用."},     
69.                    "ajaxName":{  
70.                        "file":"validateUser.php",  
71.                        "alertText":"* This name is already taken",  
72.                        "alertTextOk":"* This name is available",     
73.                        "alertTextLoad":"* Loading, please wait"}                     
74.                    }     
75.        }  
76.    }  
77.})(jQuery);  
78. 
79.$(document).ready(function() {    
80.    $.validationEngineLanguage.newLang()  
81.}); 
(function($) {
$.fn.validationEngineLanguage = function() {};
$.validationEngineLanguage = {
newLang: function() {
$.validationEngineLanguage.allRules = {"required":{    // Add your regex rules here, you can take telephone as an example
"regex":"none",
"alertText":"* 非空选项.",
"alertTextCheckboxMultiple":"* 请选择一个单选框.",
"alertTextCheckboxe":"* 请选择一个复选框."},
"length":{
"regex":"none",
"alertText":"* 长度必须在 ",
"alertText2":" 至 ",
"alertText3": " 之间."},
"maxCheckbox":{
"regex":"none",
"alertText":"* 最多选择 ",//官方文档这里有问题
"alertText2":" 项."},
"minCheckbox":{
"regex":"none",
"alertText":"* 至少选择 ",
"alertText2":" 项."},
"confirm":{
"regex":"none",
"alertText":"* 两次输入不一致,请重新输入."},
"telephone":{
"regex":"/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/",
"alertText":"* 请输入有效的电话号码,如:010-29292929."},
"mobilephone":{
"regex":"/(^0?[1][358][0-9]{9}$)/",
"alertText":"* 请输入有效的手机号码."},
"email":{
"regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
"alertText":"* 请输入有效的邮件地址."},
"date":{
                         "regex":"/^(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$/",
                         "alertText":"* 请输入有效的日期,如:2008-08-08."},
"ip":{
                         "regex":"/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/",
                         "alertText":"* 请输入有效的IP."},
"chinese":{
"regex":"/^[\u4e00-\u9fa5]+$/",
"alertText":"* 请输入中文."},
"url":{
"regex":"/^[a-zA-z]:\\/\\/[^s]$/",//这些验证请自己加强
"alertText":"* 请输入有效的网址."},
"zipcode":{
"regex":"/^[1-9]\d{5}$/",
"alertText":"* 请输入有效的邮政编码."},
"qq":{
"regex":"/^[1-9]\d{4,9}$/",
"alertText":"* 请输入有效的QQ号码."},
"onlyNumber":{
"regex":"/^[0-9]+$/",
"alertText":"* 请输入数字."},
"onlyLetter":{
"regex":"/^[a-zA-Z]+$/",
"alertText":"* 请输入英文字母."},
"noSpecialCaracters":{
"regex":"/^[0-9a-zA-Z]+$/",
"alertText":"* 请输入英文字母和数字."},
"ajaxUser":{
"file":"validate.action",//ajax验证用户名,会post如下参数:validateError ajaxUser;validateId user;validateValue cccc
"alertTextOk":"* 帐号可以使用.",
"alertTextLoad":"* 检查中, 请稍后...",
"alertText":"* 帐号不能使用."},
"ajaxName":{
"file":"validateUser.php",
"alertText":"* This name is already taken",
"alertTextOk":"* This name is available",
"alertTextLoad":"* Loading, please wait"}
}
}
}
})(jQuery);

$(document).ready(function() {
$.validationEngineLanguage.newLang()
});

部分jquery.validationEngine.js

Java代码
1./* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */     
2.            if(!ajaxisError){  
3.                $.ajax({  
4.                    type: "POST",  
5.                    url: postfile,  
6.                    async: true,  
7.                    data: "validateValue="+fieldValue+"&validateId="+fieldId+"&validateError="+customAjaxRule,//+extraData,//自己把其中的+extraData去掉了,不然后面的ajax验证有问题。  
8.                    beforeSend: function(){     // BUILD A LOADING PROMPT IF LOAD TEXT EXIST                      
9.                        if($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){  
10.                          
11.                            if(!$("div."+fieldId+"formError")[0]){                                
12.                                return $.validationEngine.buildPrompt(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");  
13.                            }else{  
14.                                $.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");  
15.                            }  
16.                        }  
17.                    }, 
/* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */
if(!ajaxisError){
$.ajax({
   type: "POST",
   url: postfile,
   async: true,
   data: "validateValue="+fieldValue+"&validateId="+fieldId+"&validateError="+customAjaxRule,//+extraData,//自己把其中的+extraData去掉了,不然后面的ajax验证有问题。
   beforeSend: function(){ // BUILD A LOADING PROMPT IF LOAD TEXT EXIST   
   if($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){
  
   if(!$("div."+fieldId+"formError")[0]){   
return $.validationEngine.buildPrompt(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
}else{
$.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
}
   }
  },

struts.xml文件:

Java代码
1. <struts>  
2.    <package name="json" extends="json-default">  
3.        <!--验证-->  
4.        <action name="validate" class="com.action.ValidateAction" 
5.            method="vali">  
6.            <result type="json"></result>  
9.        </action>  
10.          
11.    </package>  
12.</struts> 

action中的属性方法:
private JSONArray jsonValidateReturn;

public JSONArray getJsonValidateReturn() {
return jsonValidateReturn;
}

public void setJsonValidateReturn(JSONArray jsonValidateReturn) {
this.jsonValidateReturn = jsonValidateReturn;
}

1.public String vali() {  
2.        ActionContext ac = ActionContext.getContext();  
3.        HttpServletRequest request = (HttpServletRequest) ac  
4.        .get(ServletActionContext.HTTP_REQUEST);  
5.        String validateId = request.getParameter("validateId");  
6.        logger.info("vali() - String validateId=" + validateId);  
7. 
8.        String validateValue = request.getParameter("validateValue");  
9.        String validateError = request.getParameter("validateError");  
10.        logger.info("vali() - String validateError=" + validateError);  
11. //注意下面的顺序,感觉这是个缺陷之一,不过可以jquery.validationEngine.js更改, 
             jsonValidateReturn=new JSONArray();12.        jsonValidateReturn.add(validateId);  
13.        jsonValidateReturn.add(validateError);  
14.        if(validateValue.equals("chen"))  
15.        jsonValidateReturn.add("true");  
16.        else 
17.            jsonValidateReturn.add("false");  
18.        return SUCCESS;  
19.    } 

jquery.validationEngine.js要更改的地方:

Java代码
1.success: function(data){                    // GET SUCCESS DATA RETURN JSON  
2.                        data = eval( "("+data+")");             // GET JSON DATA FROM PHP AND PARSE IT  
3.                        ajaxisError = data.jsonValidateReturn[2];//这里官方文档写死了,可以根据自己需求更改。  
4.                        customAjaxRule = data.jsonValidateReturn[1];//这里官方文档写死了,可以根据自己需求更改。  
5.                        ajaxCaller = $("#"+data.jsonValidateReturn[0])[0];  
6.                        fieldId = ajaxCaller;  
7.                        ajaxErrorLength = $.validationEngine.ajaxValidArray.length;  
8.                        existInarray = false;  
9.                          
10.                         if(ajaxisError == "false"){            // DATA FALSE UPDATE PROMPT WITH ERROR;  
11.                              
12.                            _checkInArray(false)                // Check if ajax validation alreay used on this field  
13.                              
14.                            if(!existInarray){                  // Add ajax error to stop submit                  
15.                                $.validationEngine.ajaxValidArray[ajaxErrorLength] =  new Array(2);  
16.                                $.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId;  
17.                                $.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false;  
18.                                existInarray = false;  
19.                            } 
success: function(data){ // GET SUCCESS DATA RETURN JSON
data = eval( "("+data+")"); // GET JSON DATA FROM PHP AND PARSE IT
ajaxisError = data.jsonValidateReturn[2];//这里官方文档写死了,可以根据自己需求更改。
customAjaxRule = data.jsonValidateReturn[1];//这里官方文档写死了,可以根据自己需求更改。
ajaxCaller = $("#"+data.jsonValidateReturn[0])[0];
fieldId = ajaxCaller;
ajaxErrorLength = $.validationEngine.ajaxValidArray.length;
existInarray = false;

if(ajaxisError == "false"){ // DATA FALSE UPDATE PROMPT WITH ERROR;

_checkInArray(false) // Check if ajax validation alreay used on this field

if(!existInarray){ // Add ajax error to stop submit
$.validationEngine.ajaxValidArray[ajaxErrorLength] =  new Array(2);
$.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId;
$.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false;
existInarray = false;
}

----------------------------------
struts2-json-plugin的配置问题
JSON(Java Script Object Notation),是一种语言无关的数据交换格式。JSON插件是Structs 2 的Ajax插件,通过利用JSON插件,开发者可以很方便,灵活的利用Ajax进行开发。Json是一种轻量级的数据交换格式,JSon插件提供了一种名为json的Action ResultType 。一旦为Action指定了该结果处理类型,JSON插件就会自动将Action里的数据序列化成JSON格式的数据,并返回给客户端物理视图的JavaScript。简单的说,JSON插件允许我们在JavaScript中异步的调用Action,而且Action不需要指定视图来显示Action的信息显示。而是由JSON插件来负责具体将Action里面具体的信息返回给调用页面。

Json的数据格式可简单如下形式: person = { name: 'Jim',age: 18,gender: 'man'}。

如果action的属性很多,我们想要从Action返回到调用页面的数据。这个时候配置includeProperties或者excludeProperties拦截器即可。而这2个拦截器的定义都在struts2的json-default包内,所以要使用该拦截器的包都要继承自json-default。

Xml代码

<struts>  
     <constant name="struts.objectFactory" value="spring"/>        
     <include file="struts-admin.xml"></include>   
     <package name="default" extends="json-default">   
         <action name="person" class="com.person.PersonAction" method="view">  
         <result type="json">  
            <param name="includeProperties">              
             person\.name,persoon\.age,person\.gender              
            </param>>              
         </result>  
         </action>  
     </package>          
</struts> 
利用Struts 2的支持的可配置结果,可以达到过滤器的效果。Action的处理结果配置支持正则表达式。

但是如果返回的对象是一个数组格式的Json数据。比如peson Bean中有对象persion1...person9,而我只要person1的json数据,则可以用如下的正则表达式。

Xml代码

<struts>  
     <constant name="struts.objectFactory" value="spring"/>        
     <include file="struts-admin.xml"></include>   
     <package name="default" extends="json-default">   
         <action name="person" class="com.person.PersonAction" method="view">  
         <result type="json">  
            <param name="includeProperties">              
             person\[\d+\]\.person1   
            </param>>              
         </result>  
         </action>  
     </package>          
</struts> 
excludeProperties拦截器的用法与此类同,如果拦截的仅仅是一个对象,如果拦截掉person Bean的整个对象。

Xml代码

<struts>  
     <constant name="struts.objectFactory" value="spring"/>        
     <include file="struts-admin.xml"></include>   
     <package name="default" extends="json-default">   
         <action name="person" class="com.person.PersonAction" method="view">  
         <result type="json">  
            <param name="excludeProperties">              
             person   
            </param>>              
         </result>  
         </action>  
     </package>          
</struts> 
需要注意的是,如果用JSON插件把返回结果定为JSON。而JSON的原理是在ACTION中的get方法都会序列化,

所以前面是get的方法只要没指定不序列化,都会执行。

如果该方法一定要命名为get*(比如实现了什么接口),

那么可以在该方法的前面加注解声明该方法不做序列化。

注解的方式为:@JSON(serialize=false)

除此之外,JSON注释还支持如下几个域:

serialize:设置是否序列化该属性

deserialize:设置是否反序列化该属性。

format:设置用于格式化输出、解析日期表单域的格式。例如"yyyy-MM-dd'T'HH:mm:ss"。

//使用注释语法来改变该属性序列化后的属性名

@JSON(name="newName")

public String getName()

{

return this.name;

}

需要引入 import com.googlecode.jsonplugin.annotations.JSON;

@JSON(serialize=false)

public User getUser() {

    return this.User;

}

@JSON(format="yyyy-MM-dd")

public Date getStartDate() {

    return this.startDate;

}
原创粉丝点击