validationEngine中文版 — jquery强大的表单验证插件

中文汉化版,官方只有英文的。同时根据中国国情修改了部分验证规则。

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

官方下载地址:http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

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

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

一:简单说明下使用教程:

引入jquery和插件js、css

  1. <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />
  2. <script src="js/jquery.js" type="text/javascript"></script>
  3. <script src="js/jquery.validationEngine-en.js" type="text/javascript"></script>
  4. <script src="js/jquery.validationEngine.js" type="text/javascript"></script>

jquery.validationEngine-en.js是语言文件,所有的提示都在这个文件找的到,可以很方便的转成其他语言,同时你也可以在这个文件内定制属于自己的验证规则。

初始化插件

  1. $(document).ready(function() {
  2. $("#formID").validationEngine()
  3. })

验证规则是写在表单元素的class属性内。比如下面:

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

验证规则非常多样,基本上包含了所有的数据类型的验证。
所有的验证规则写在validate[]内,有多种验证,用逗号隔开,这里简要说明下常用的验证规则。

  1. required:值不可以为空
  2. length[0,100] :文字允许长度
  3. confirm[fieldID] :匹配其他的表单元素的值,fieldID就是其他表单元素的id,这个主要用于再次确认密码
  4. telephone :数据格式要求符合电话格式
  5. email : 数据格式要求符合email 格式
  6. onlyNumber :只允许输入数字
  7. noSpecialCaracters :不允许出现特殊字符
  8. onlyLetter : 只能是字母
  9. date :必须符合日期格式YYYY-MM-DD

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

  1. $("#formID").validationEngine({
  2. inlineValidation: false,
  3. success : false,
  4. failure : function() { callFailFunction() }
  5. })

默认的是在鼠标失去焦点后才开始验证,也就是绑定的是blur事件,那如何改变呢?看下面的配置。

  1. $("#formID").validationEngine({
  2. validationEventTriggers:"keyup blur", //will validate on keyup and blur
  3. success : false,
  4. failure : function() { callFailFunction() }
  5. })

validationEventTriggers属性就是修改绑定事件,上面是增加了个keyup,也就是键盘按键起来就触发验证。

修改提示层的位置

  1. $("#formID").validationEngine({
  2. promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
  3. success : false,
  4. failure : function() {
  5. })

promptPosition就是控制位置,有5种模式:topLeft, topRight, bottomLeft, centerRight, bottomRight

ajax验证模式

  1. $("#formID").validationEngine({
  2.  ajaxSubmit: true,
  3.  ajaxSubmitFile: "ajaxSubmit.php",
  4.  ajaxSubmitMessage: "Thank you, we received your inscription!",
  5.  ajaxSubmitExtraData: "securityCode=38709238423&name=john",
  6.  success : false,
  7.  failure : function() {}
  8. })

这几个参数很好理解。

  1. ajaxSubmit: true, 提交表单使用ajax提交
  2. ajaxSubmitFile: “ajaxSubmit.php”, 后台脚本
  3. ajaxSubmitMessage 成功后显示的信息
  4. ajaxSubmitExtraData 参数

这里需要对后台脚本返回的数据进行下说明:
返回的数据格式是json。
出现一个错误,产生一个数组,如下:

  1. $arrayError[0][0] = "#email"; // FIELDID
  2. $arrayError[0][1] = "Your email do not match.. whatever it need to match"; // TEXT ERROR
  3. $arrayError[0][2] = "error"; // BOX COLOR

二:修改过的地方

解决ie6下select遮挡div的办法
jquery.validationEngine.js要修改的地方:

Xml代码
  1. calculatedPosition.callerTopPosition += "px";
  2. calculatedPosition.callerleftPosition += "px";
  3. calculatedPosition.marginTopSize += "px";
  4. //add matychen
  5. if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
  6. $(divFormError).append('<iframe class="iframe" frameborder="0" scr="javascript:false;"></iframe>');
  7. }
  8. // add matychen
  9. $(divFormError).css({
  10. "top": calculatedPosition.callerTopPosition,
  11. "left": calculatedPosition.callerleftPosition,
  12. "marginTop": calculatedPosition.marginTopSize,
  13. "opacity": 0
  14. });


validationEngine.jquery.css里面加入以下代码:

Java代码
  1. .iframe {
  2. position: absolute;
  3. width: expression(this.parentNode.offsetWidth+\'px\');
  4. height: expression(this.parentNode.offsetHeight-32+\'px\');
  5. z-index: -1;
  6. top: expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\');
  7. left: expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\');
  8. }

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. <body>
  30. <form id="formID" class="formular" method="post" action="">
  31. <fieldset>
  32. <legend>User informations</legend>
  33. <label>
  34. <span>Desired username (ajax validation, only karnius is available) : </span>
  35. <input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" />//ajax验证用户名的地方
  36. </label>
  37. <label>
  38. <span>First name (optional)</span>
  39. <input value="karnius" class="validate[optional,custom[onlyLetter],length[0,100]] text-input" type="text" name="firstname" id="firstname" />
  40. </label>
  41. <label>
  42. <span>Last name : </span>
  43. <input value="karnius" class="validate[required,custom[onlyLetter],length[0,100]] text-input" type="text" id="data[Use6][preferedColor]" name="lastname" />
  44. </label>
  45. <div>
  46. <span>Radio Groupe : <br /></span>
  47. <span>radio 1: </span>
  48. <input class="validate[required] radio" type="radio" name="data[User][preferedColor]" id="radio1" value="5">
  49. <span>radio 2: </span>
  50. <input class="validate[required] radio" type="radio" name="data[User][preferedColor]" id="radio2" value="3"/>
  51. <span>radio 3: </span>
  52. <input class="validate[required] radio" type="radio" name="data[User][preferedColor]" id="radio3" value="9"/>
  53. </div>
  54. <div>
  55. <span>Minimum 2 checkbox : <br /></span>
  56. <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5">
  57. <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5">
  58. <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck2" value="3"/>
  59. <input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck3" value="9"/>
  60. </div>
  61. <label>
  62. <span>Date : (format YYYY-MM-DD)</span>
  63. <input value="1111-11-11" class="validate[required,custom[date]] text-input" type="text" name="date" id="date" />
  64. </label>
  65. <label>
  66. <span>Favorite sport 1:</span>
  67. <select name="sport" id="sport" class="validate[required]" id="sport" >
  68. <option value="">Choose a sport</option>
  69. <option value="option1">Tennis</option>
  70. <option value="option2">Football</option>
  71. <option value="option3">Golf</option>
  72. </select>
  73. </label>
  74. <label>
  75. <span>Favorite sport 2:</span>
  76. <select name="sport2" id="sport2" multiple class="validate[required]" id="sport2" >
  77. <option value="">Choose a sport</option>
  78. <option value="option1">Tennis</option>
  79. <option value="option2">Football</option>
  80. <option value="option3">Golf</option>
  81. </select>
  82. </label>
  83. <label>
  84. <span>Age : </span>
  85. <input value="22" class="validate[required,custom[onlyNumber],length[0,3]] text-input" type="text" name="age" id="age" />
  86. </label>
  87. <label>
  88. <span>Telephone : </span>
  89. <input value="1111111" class="validate[required,custom[telephone]] text-input" type="text" name="telephone" id="telephone" />
  90. </label>
  91. <label>
  92. <span>mobilephone : </span>
  93. <input value="111111" class="validate[required,custom[mobilephone]] text-input" type="text" name="telphone" id="telphone" />
  94. </label>
  95. <label>
  96. <span>chinese : </span>
  97. <input value="asdf" class="validate[required,custom[chinese]] text-input" type="text" name="chinese" id="chinese" />
  98. </label>
  99. <label>
  100. <span>url : </span>
  101. <input value="url" class="validate[required,custom[url]] text-input" type="text" name="url" id="url" />
  102. </label>
  103. <label>
  104. <span>zipcode : </span>
  105. <input value="zipcode" class="validate[required,custom[zipcode]] text-input" type="text" name="zipcode" id="zipcode" />
  106. </label>
  107. <label>
  108. <span>ip : </span>
  109. <input value="ip" class="validate[required,custom[ip]] text-input" type="text" name="ip" id="ip" />
  110. </label>
  111. <label>
  112. <span>qq : </span>
  113. <input value="01234" class="validate[required,custom[qq]] text-input" type="text" name="qq" id="qq" />
  114. </label>
  115. </fieldset>
  116. <fieldset>
  117. <legend>Password</legend>
  118. <label>
  119. <span>Password : </span>
  120. <input value="karnius" class="validate[required,length[6,11]] text-input" type="password" name="password" id="password" />
  121. </label>
  122. <label>
  123. <span>Confirm password : </span>
  124. <input value="karnius" class="validate[required,confirm[password]] text-input" type="password" name="password2" id="password2" />
  125. </label>
  126. </fieldset>
  127. <fieldset>
  128. <legend>Email</legend>
  129. <label>
  130. <span>Email address : </span>
  131. <input value="ced@hotmail.com" class="validate[required,custom[email]] text-input" type="text" name="email" id="email" />
  132. </label>
  133. <label>
  134. <span>Confirm email address : </span>
  135. <input value="ced@hotmail.com" class="validate[required,confirm[email]] text-input" type="text" name="email2" id="email2" />
  136. </label>
  137. </fieldset>
  138. <fieldset>
  139. <legend>Comments</legend>
  140. <label>
  141. <span>Comments : </span>
  142. <textarea value="ced@hotmail.com" class="validate[required,length[6,300]] text-input" name="comments" id="comments" /> </textarea>
  143. </label>
  144. </fieldset>
  145. <fieldset>
  146. <legend>Conditions</legend>
  147. <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>
  148. <label>
  149. <span class="checkbox">I accept terms of use : </span>
  150. <input class="validate[required] checkbox" type="checkbox" id="agree" name="agree"/>
  151. </label>
  152. </fieldset>
  153. <input class="submit" type="submit" value="Validate & Send the form!"/>
  154. <hr/>
  155. </form>
  156. </body>
  157. </html>
 
jquery.validationEngine-cn.js如下:
Java代码
  1. (function($) {
  2. $.fn.validationEngineLanguage = function() {};
  3. $.validationEngineLanguage = {
  4. newLang: function() {
  5. $.validationEngineLanguage.allRules = {"required":{ // Add your regex rules here, you can take telephone as an example
  6. "regex":"none",
  7. "alertText":"* 非空选项.",
  8. "alertTextCheckboxMultiple":"* 请选择一个单选框.",
  9. "alertTextCheckboxe":"* 请选择一个复选框."},
  10. "length":{
  11. "regex":"none",
  12. "alertText":"* 长度必须在 ",
  13. "alertText2":" 至 ",
  14. "alertText3": " 之间."},
  15. "maxCheckbox":{
  16. "regex":"none",
  17. "alertText":"* 最多选择 ",//官方文档这里有问题
  18. "alertText2":" 项."},
  19. "minCheckbox":{
  20. "regex":"none",
  21. "alertText":"* 至少选择 ",
  22. "alertText2":" 项."},
  23. "confirm":{
  24. "regex":"none",
  25. "alertText":"* 两次输入不一致,请重新输入."},
  26. "telephone":{
  27. "regex":"/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/",
  28. "alertText":"* 请输入有效的电话号码,如:010-29292929."},
  29. "mobilephone":{
  30. "regex":"/(^0?[1][358][0-9]{9}$)/",
  31. "alertText":"* 请输入有效的手机号码."},
  32. "email":{
  33. "regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
  34. "alertText":"* 请输入有效的邮件地址."},
  35. "date":{
  36. "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)$/",
  37. "alertText":"* 请输入有效的日期,如:2008-08-08."},
  38. "ip":{
  39. "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]?)$/",
  40. "alertText":"* 请输入有效的IP."},
  41. "chinese":{
  42. "regex":"/^[\u4e00-\u9fa5]+$/",
  43. "alertText":"* 请输入中文."},
  44. "url":{
  45. "regex":"/^[a-zA-z]:\\/\\/[^s]$/",//这些验证请自己加强
  46. "alertText":"* 请输入有效的网址."},
  47. "zipcode":{
  48. "regex":"/^[1-9]\d{5}$/",
  49. "alertText":"* 请输入有效的邮政编码."},
  50. "qq":{
  51. "regex":"/^[1-9]\d{4,9}$/",
  52. "alertText":"* 请输入有效的QQ号码."},
  53. "onlyNumber":{
  54. "regex":"/^[0-9]+$/",
  55. "alertText":"* 请输入数字."},
  56. "onlyLetter":{
  57. "regex":"/^[a-zA-Z]+$/",
  58. "alertText":"* 请输入英文字母."},
  59. "noSpecialCaracters":{
  60. "regex":"/^[0-9a-zA-Z]+$/",
  61. "alertText":"* 请输入英文字母和数字."},
  62. "ajaxUser":{
  63. "file":"validate.action",//ajax验证用户名,会post如下参数:validateError ajaxUser;validateId user;validateValue cccc
  64. "alertTextOk":"* 帐号可以使用.",
  65. "alertTextLoad":"* 检查中, 请稍后...",
  66. "alertText":"* 帐号不能使用."},
  67. "ajaxName":{
  68. "file":"validateUser.php",
  69. "alertText":"* This name is already taken",
  70. "alertTextOk":"* This name is available",
  71. "alertTextLoad":"* Loading, please wait"}
  72. }
  73. }
  74. }
  75. })(jQuery);
  76. $(document).ready(function() {
  77. $.validationEngineLanguage.newLang()
  78. });
部分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. if(!$("div."+fieldId+"formError")[0]){
  11. return $.validationEngine.buildPrompt(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
  12. }else{
  13. $.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
  14. }
  15. }
  16. },

struts.xml文件:

Java代码
  1. <struts>
  2. <package name="json" extends="json-default">
  3. <!--验证-->
  4. <action name="validate" class="com.bw30.zjvote.action.ValidateAction"
  5. method="vali">
  6. <result type="json">
  7. <param name="excludeProperties">msg</param>//jsonplugin-0.32.jar
  8. </result>
  9. </action>
  10. </package>
  11. </struts>


validateAction

Java代码
  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. String validateValue = request.getParameter("validateValue");
  8. String validateError = request.getParameter("validateError");
  9. logger.info("vali() - String validateError=" + validateError);
  10. //注意下面的顺序,感觉这是个缺陷之一,不过可以在jquery.validationEngine.js更改,
  11. jsonValidateReturn.add(validateId);
  12. jsonValidateReturn.add(validateError);
  13. if(validateValue.equals("chen"))
  14. jsonValidateReturn.add("true");
  15. else
  16. jsonValidateReturn.add("false");
  17. return SUCCESS;
  18. }

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. if(ajaxisError == "false"){ // DATA FALSE UPDATE PROMPT WITH ERROR;
  10. _checkInArray(false) // Check if ajax validation alreay used on this field
  11. if(!existInarray){ // Add ajax error to stop submit
  12. $.validationEngine.ajaxValidArray[ajaxErrorLength] = new Array(2);
  13. $.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId;
  14. $.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false;
  15. existInarray = false;
  16. }
 
用到了jsonplugin-0.32.jar这个包在附件里面,其他struts的包,自己添加。

posted @ 2011-03-21 15:11  rob_2010  阅读(205)  评论(0)    收藏  举报