首页 > 开发 > AJAX > 正文

自己编写的支持Ajax验证的JS表单验证插件

2024-09-01 08:33:01
字体:大 中 小
来源:转载
供稿:网友

创建一个JavaScript表单验证插件,可以说是一个繁琐的过程,涉及到初期设计、开发与测试等等环节。实际上一个优秀的程序员不仅是技术高手,也应该是善假于外物的。本文介绍的这个不错的JavaScript表单验证插件,支持ajax验证,有需要的小伙伴可以参考下

自己编写了一个表单验证插件,支持ajax验证,使用起来很简单。

每个需要验证的表单元素下面有一个span标签,这个标签的class有一个valid表示需要验证,如果有nullable则表示可为空;rule表示验证规则,msg表示错误提示信息;to表示要验证的元素的name值,如果元素是单个的,to可以不写。该插件会遍历每个有valid的span标签,找出它前面需要验证的元素,根据rule验证,如果验证不通过,则显示边框为红色,鼠标放在元素上时显示错误信息。

验证时机:1、点击提交按钮时显式调用验证方法;2、当元素触发blur时验证。

插件代码:

CSS:

 

 
  1. .failvalid 
  2. { 
  3. border: solid 2px red !important; 
  4. } 

JS:

 

 
  1. /** 
  2. * suxiang 
  3. * 2014年12月22日 
  4. * 验证插件 
  5. */ 
  6.  
  7. SimpoValidate = { 
  8. //验证规则 
  9. rules: { 
  10. int: /^[1-9]/d*$/, 
  11. number: /^[+-]?/d*/.?/d+$/ 
  12. }, 
  13.  
  14. //初始化 
  15. init: function () { 
  16. $(".valid").each(function () { //遍历span 
  17. if ($(this)[0].tagName.toLowerCase() == "span") { 
  18. var validSpan = $(this); 
  19. var to = validSpan.attr("to"); 
  20. var target; 
  21. if (to) { 
  22. target = $("input[name='" + to + "'],select[name='" + to + "'],textarea[name='" + to + "']"); 
  23. } else { 
  24. var target = validSpan.prev(); 
  25. } 
  26. if (target) { 
  27. target.blur(function () { 
  28. SimpoValidate.validOne(target, validSpan); 
  29. }); 
  30. } 
  31. } 
  32. }); 
  33. }, 
  34.  
  35. //验证全部,验证成功返回true 
  36. valid: function () { 
  37. SimpoValidate.ajaxCheckResult = true; 
  38. var bl = true; 
  39.  
  40. $(".valid").each(function () { //遍历span 
  41. if ($(this)[0].tagName.toLowerCase() == "span") { 
  42. var validSpan = $(this); 
  43. var to = validSpan.attr("to"); 
  44. var target; 
  45. if (to) { 
  46. target = $("input[name='" + to + "'],select[name='" + to + "'],textarea[name='" + to + "']"); 
  47. } else { 
  48. target = validSpan.prev(); 
  49. } 
  50. if (target) { 
  51. if (!SimpoValidate.validOne(target, validSpan)) { 
  52. bl = false; 
  53. } 
  54. } 
  55. } 
  56. }); 
  57.  
  58. return bl && SimpoValidate.ajaxCheckResult; 
  59. }, 
  60.  
  61. //单个验证,验证成功返回true 
  62. validOne: function (target, validSpan) { 
  63. SimpoValidate.removehilight(target, msg); 
  64.  
  65. var rule = SimpoValidate.getRule(validSpan); 
  66. var msg = validSpan.attr("msg"); 
  67. var nullable = validSpan.attr("class").indexOf("nullable") == -1 ? false : true; //是否可为空 
  68. var to = validSpan.attr("to"); 
  69. var ajaxAction = validSpan.attr("ajaxAction"); 
  70.  
  71. if (target) { 
  72. //checkbox或radio 
  73. if (target[0].tagName.toLowerCase() == "input" && target.attr("type") && (target.attr("type").toLowerCase() == "checkbox" || target.attr("type").toLowerCase() == "radio")) { 
  74. var checkedInput = $("input[name='" + to + "']:checked"); 
  75. if (!nullable) { 
  76. if (checkedInput.length == 0) { 
  77. SimpoValidate.hilight(target, msg); 
  78. return false; 
  79. } 
  80. } 
  81. } 
  82.  
  83. //input或select 
  84. if (target[0].tagName.toLowerCase() == "input" || target[0].tagName.toLowerCase() == "select") { 
  85. var val = target.val(); 
  86. if (!nullable) { 
  87. if ($.trim(val) == "") { 
  88. SimpoValidate.hilight(target, msg); 
  89. return false; 
  90. } 
  91. } 
  92. else { 
  93. if ($.trim(val) == "") { 
  94. SimpoValidate.removehilight(target, msg); 
  95. return true; 
  96. } 
  97. } 
  98.  
  99. if (rule) { 
  100. var reg = new RegExp(rule); 
  101. if (!reg.test(val)) { 
  102. SimpoValidate.hilight(target, msg); 
  103. return false; 
  104. } 
  105. } 
  106.  
  107. if (ajaxAction) { 
  108. SimpoValidate.ajaxCheck(target, val, ajaxAction); 
  109. } 
  110. } 
  111. else if (target[0].tagName.toLowerCase() == "textarea") { 
  112. var val = target.text(); 
  113. if (!nullable) { 
  114. if ($.trim(val) == "") { 
  115. SimpoValidate.hilight(target, msg); 
  116. return false; 
  117. } 
  118. } 
  119. else { 
  120. if ($.trim(val) == "") { 
  121. SimpoValidate.removehilight(target, msg); 
  122. return true; 
  123. } 
  124. } 
  125.  
  126. if (rule) { 
  127. var reg = new RegExp(rule); 
  128. if (!reg.test(val)) { 
  129. SimpoValidate.hilight(target, msg); 
  130. return false; 
  131. } 
  132. } 
  133.  
  134. if (ajaxAction) { 
  135. SimpoValidate.ajaxCheck(target, val, ajaxAction); 
  136. } 
  137. } 
  138. } 
  139.  
  140. return true; 
  141. }, 
  142.  
  143. ajaxCheckResult: true, 
  144.  
  145. ajaxCheck: function (target, value, ajaxAction) { 
  146. var targetName = target.attr("name"); 
  147. var data = new Object(); 
  148. data[targetName] = value; 
  149.  
  150. $.ajax({ 
  151. url: ajaxAction, 
  152. type: "POST", 
  153. data: data, 
  154. async: false, 
  155. success: function (data) { 
  156. if (data.data == true) { 
  157. SimpoValidate.removehilight(target); 
  158. } 
  159. else { 
  160. SimpoValidate.ajaxCheckResult = false; 
  161. SimpoValidate.hilight(target, data.data); 
  162. } 
  163. } 
  164. }); 
  165. }, 
  166.  
  167. //获取验证规则 
  168. getRule: function (validSpan) { 
  169. var rule = validSpan.attr("rule"); 
  170. switch ($.trim(rule)) { 
  171. case "int": 
  172. return this.rules.int; 
  173. case "number": 
  174. return this.rules.number; 
  175. default: 
  176. return rule; 
  177. break; 
  178. } 
  179. }, 
  180.  
  181. //红边框及错误提示 
  182. hilight: function (target, msg) { 
  183. target.addClass("failvalid"); 
  184. target.bind("mouseover", function (e) { 
  185. SimpoValidate.tips(target, msg, e); 
  186. }); 
  187. target.bind("mouseout", function () { 
  188. SimpoValidate.removetips(); 
  189. }); 
  190. }, 
  191.  
  192. //取消红边框及错误提示 
  193. removehilight: function (target) { 
  194. target.unbind("mouseover"); 
  195. target.unbind("mouseout"); 
  196. target.removeClass("failvalid"); 
  197. SimpoValidate.removetips(); 
  198. }, 
  199.  
  200. //显示提示 
  201. tips: function (target, text, e) { 
  202. var divtipsstyle = "position: absolute; z-index:99999; left: 0; top: 0; background-color: #dceaf2; padding: 3px; border: solid 1px #6dbde4; visibility: hidden; line-height:20px; font-size:12px;"; 
  203. $("body").append("<div class='div-tips' style='" + divtipsstyle + "'>" + text + "</div>"); 
  204.  
  205. var divtips = $(".div-tips"); 
  206. divtips.css("visibility", "visible"); 
  207.  
  208. var top = e.clientY + $(window).scrollTop() - divtips.height() - 18; 
  209. var left = e.clientX; 
  210. divtips.css("top", top); 
  211. divtips.css("left", left); 
  212.  
  213. $(target).mousemove(function (e) { 
  214. var top = e.clientY + $(window).scrollTop() - divtips.height() - 18; 
  215. var left = e.clientX; 
  216. divtips.css("top", top); 
  217. divtips.css("left", left); 
  218. }); 
  219. }, 
  220.  
  221. //移除提示 
  222. removetips: function () { 
  223. $(".div-tips").remove(); 
  224. } 
  225. }; 
  226.  
  227. $(function () { 
  228. SimpoValidate.init(); 
  229. }); 

如何使用:

Edit页面:

 

 
  1. @using Model.Suya; 
  2. @{ 
  3. ViewBag.Title = "Add"; 
  4. Layout = "~/Views/Shared/_Layout.cshtml"; 
  5. } 
  6. @{ 
  7. List<sys_post> postList = (List<sys_post>)ViewData["postList"]; 
  8. sys_post post = (sys_post)ViewData["post"]; 
  9. } 
  10. <script type="text/javascript"> 
  11. $(function () { 
  12. //部门树 
  13. $('#dept').combotree({ 
  14. url: 'GetDeptTree', 
  15. required: false, 
  16. checkbox: true, 
  17. onLoadSuccess: function () { 
  18. $('#dept').combotree('setValue', "@(post.depCode)"); 
  19. } 
  20. }); 
  21.  
  22. //操作结果 
  23. $("#ifrm").load(function (data) { 
  24. var data = eval("(" + $("#ifrm").contents().find("body").html() + ")"); 
  25. alert(data.msg); 
  26. if (data.ok) back(); 
  27. }); 
  28.  
  29. $("select[name='postLevel']").find("option[value='@(post.postLevel)']").attr("selected", "selected"); 
  30. }); 
  31.  
  32. //保存 
  33. function save() { 
  34. if (valid()) { 
  35. $("#frm").submit(); 
  36. } 
  37. } 
  38.  
  39. //验证 
  40. function valid() { 
  41. var dept = $("input[name='dept']"); 
  42. if (!dept.val()) { 
  43. SimpoValidate.hilight(dept.parent(), "请选择所属部门"); 
  44. } else { 
  45. SimpoValidate.removehilight(dept.parent()); 
  46. } 
  47.  
  48. return SimpoValidate.valid(); 
  49. } 
  50.  
  51. //返回 
  52. function back() { 
  53. parent.$('#ttTab').tabs('select', "岗位管理"); 
  54. var tab = parent.$('#ttTab').tabs('getSelected'); 
  55. tab.find("iframe").contents().find("#btnSearch").click(); 
  56. parent.$("#ttTab").tabs('close', '修改岗位信息'); 
  57. } 
  58. </script> 
  59. <div class="tiao"> 
  60. <input type="button" class="submit_btn" value="保存" onclick="save()" /> 
  61. <input type="button" class="submit_btn" value="返回" onclick="back()" /> 
  62. </div> 
  63. <iframe id="ifrm" name="ifrm" style="display: none;"></iframe> 
  64. <form id="frm" method="post" enctype="multipart/form-data" action="/HR/PostManage/SaveEdit?id=@(post.id)" 
  65. target="ifrm"> 
  66. <div class="adminMainContent"> 
  67. <div class="box"> 
  68. <div class="box-title"> 
  69. 基础信息 
  70. </div> 
  71. <div class="box-content"> 
  72. <table cellpadding="0" cellspacing="0" class="detail" width="100%"> 
  73. <tr> 
  74. <td class="title"> 
  75. <span class="mst">*</span>岗位名称: 
  76. </td> 
  77. <td style="width: 35%;"> 
  78. <input type="text" class="xinxi_txt" name="postName" value="@post.postName" /> 
  79. <span class="valid" msg="必填,且长度不能超过50" rule="^(.|/n){0,50}$"></span> 
  80. </td> 
  81. <td class="title"> 
  82. <span class="mst">*</span>岗位编号: 
  83. </td> 
  84. <td style="width: 35%;"> 
  85. <input type="text" class="xinxi_txt" name="postCode" value="@post.postCode" /> 
  86. <span class="valid" msg="必填,且长度不能超过20" rule="^(.|/n){0,20}$" ajaxaction="/HR/PostManage/AjaxCheckPostCode?id=@post.id"> 
  87. </span> 
  88. </td> 
  89. </tr> 
  90. <tr> 
  91. <td class="title"> 
  92. <span class="mst">*</span> 所属部门: 
  93. </td> 
  94. <td style="width: 35%;"> 
  95. <input type="text" name="depCode" id="dept" class="easyui-combotree" style="height: 30px;" /> 
  96. </td> 
  97. <td class="title"> 
  98. <span class="mst">*</span>汇报对象: 
  99. </td> 
  100. <td style="width: 35%;"> 
  101. <select class="xueli" name="reportPostCode" id="agreementType"> 
  102. <option value="" selected="selected">==请选择==</option> 
  103. @foreach (sys_post item in postList) 
  104. { 
  105. if (item.postCode == post.reportPostCode) 
  106. { 
  107. <option value="@item.postCode" selected="selected">@item.postName</option> 
  108. } 
  109. else 
  110. { 
  111. <option value="@item.postCode">@item.postName</option> 
  112. } 
  113. } 
  114. </select> 
  115. <span class="valid" msg="请选择合同分类"> 
  116. </td> 
  117. </tr> 
  118. <tr> 
  119. <td class="title"> 
  120. <span class="mst">*</span>岗位级别: 
  121. </td> 
  122. <td style="width: 35%;"> 
  123. <select class="xueli" name="postLevel"> 
  124. <option value="" selected="selected">==请选择==</option> 
  125. <option value="1">1</option> 
  126. <option value="2">2</option> 
  127. <option value="3">3</option> 
  128. <option value="4">4</option> 
  129. <option value="5">5</option> 
  130. <option value="6">6</option> 
  131. </select> 
  132. <span class="valid" msg="请选择岗位级别"> 
  133. </td> 
  134. <td class="title"> 
  135. </td> 
  136. <td style="width: 35%;"> 
  137. </td> 
  138. </tr> 
  139. <tr> 
  140. <td class="title"> 
  141. <span class="mst">*</span>备注: 
  142. </td> 
  143. <td colspan="3" style="width: 35%;"> 
  144. <textarea name="remarks" style="width: 500px;">@post.remarks</textarea> 
  145. <span class="valid" msg="长度不得超过500" rule="^(.|/n){0,500}$"></span> 
  146. </td> 
  147. </tr> 
  148. </table> 
  149. </div> 
  150. </div> 
  151. </div> 
  152. </form> 

效果图:

自己编写的支持Ajax验证的JS表单验证插件

以上所述就是本文的全部内容了,希望大家能够喜欢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表