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


Posted in Javascript onMay 15, 2015

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

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

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

插件代码:

CSS:

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

JS:

/**
* suxiang
* 2014年12月22日
* 验证插件
*/

SimpoValidate = {
 //验证规则
 rules: {
  int: /^[1-9]\d*$/,
  number: /^[+-]?\d*\.?\d+$/
 },

 //初始化
 init: function () {
  $(".valid").each(function () { //遍历span
   if ($(this)[0].tagName.toLowerCase() == "span") {
    var validSpan = $(this);
    var to = validSpan.attr("to");
    var target;
    if (to) {
     target = $("input[name='" + to + "'],select[name='" + to + "'],textarea[name='" + to + "']");
    } else {
     var target = validSpan.prev();
    }
    if (target) {
     target.blur(function () {
      SimpoValidate.validOne(target, validSpan);
     });
    }
   }
  });
 },

 //验证全部,验证成功返回true
 valid: function () {
  SimpoValidate.ajaxCheckResult = true;
  var bl = true;

  $(".valid").each(function () { //遍历span
   if ($(this)[0].tagName.toLowerCase() == "span") {
    var validSpan = $(this);
    var to = validSpan.attr("to");
    var target;
    if (to) {
     target = $("input[name='" + to + "'],select[name='" + to + "'],textarea[name='" + to + "']");
    } else {
     target = validSpan.prev();
    }
    if (target) {
     if (!SimpoValidate.validOne(target, validSpan)) {
      bl = false;
     }
    }
   }
  });

  return bl && SimpoValidate.ajaxCheckResult;
 },

 //单个验证,验证成功返回true
 validOne: function (target, validSpan) {
  SimpoValidate.removehilight(target, msg);

  var rule = SimpoValidate.getRule(validSpan);
  var msg = validSpan.attr("msg");
  var nullable = validSpan.attr("class").indexOf("nullable") == -1 ? false : true; //是否可为空
  var to = validSpan.attr("to");
  var ajaxAction = validSpan.attr("ajaxAction");

  if (target) {
   //checkbox或radio
   if (target[0].tagName.toLowerCase() == "input" && target.attr("type") && (target.attr("type").toLowerCase() == "checkbox" || target.attr("type").toLowerCase() == "radio")) {
    var checkedInput = $("input[name='" + to + "']:checked");
    if (!nullable) {
     if (checkedInput.length == 0) {
      SimpoValidate.hilight(target, msg);
      return false;
     }
    }
   }

   //input或select
   if (target[0].tagName.toLowerCase() == "input" || target[0].tagName.toLowerCase() == "select") {
    var val = target.val();
    if (!nullable) {
     if ($.trim(val) == "") {
      SimpoValidate.hilight(target, msg);
      return false;
     }
    }
    else {
     if ($.trim(val) == "") {
      SimpoValidate.removehilight(target, msg);
      return true;
     }
    }

    if (rule) {
     var reg = new RegExp(rule);
     if (!reg.test(val)) {
      SimpoValidate.hilight(target, msg);
      return false;
     }
    }

    if (ajaxAction) {
     SimpoValidate.ajaxCheck(target, val, ajaxAction);
    }
   }
   else if (target[0].tagName.toLowerCase() == "textarea") {
    var val = target.text();
    if (!nullable) {
     if ($.trim(val) == "") {
      SimpoValidate.hilight(target, msg);
      return false;
     }
    }
    else {
     if ($.trim(val) == "") {
      SimpoValidate.removehilight(target, msg);
      return true;
     }
    }

    if (rule) {
     var reg = new RegExp(rule);
     if (!reg.test(val)) {
      SimpoValidate.hilight(target, msg);
      return false;
     }
    }

    if (ajaxAction) {
     SimpoValidate.ajaxCheck(target, val, ajaxAction);
    }
   }
  }

  return true;
 },

 ajaxCheckResult: true,

 ajaxCheck: function (target, value, ajaxAction) {
  var targetName = target.attr("name");
  var data = new Object();
  data[targetName] = value;

  $.ajax({
   url: ajaxAction,
   type: "POST",
   data: data,
   async: false,
   success: function (data) {
    if (data.data == true) {
     SimpoValidate.removehilight(target);
    }
    else {
     SimpoValidate.ajaxCheckResult = false;
     SimpoValidate.hilight(target, data.data);
    }
   }
  });
 },

 //获取验证规则
 getRule: function (validSpan) {
  var rule = validSpan.attr("rule");
  switch ($.trim(rule)) {
   case "int":
    return this.rules.int;
   case "number":
    return this.rules.number;
   default:
    return rule;
    break;
  }
 },

 //红边框及错误提示
 hilight: function (target, msg) {
  target.addClass("failvalid");
  target.bind("mouseover", function (e) {
   SimpoValidate.tips(target, msg, e);
  });
  target.bind("mouseout", function () {
   SimpoValidate.removetips();
  });
 },

 //取消红边框及错误提示
 removehilight: function (target) {
  target.unbind("mouseover");
  target.unbind("mouseout");
  target.removeClass("failvalid");
  SimpoValidate.removetips();
 },

 //显示提示
 tips: function (target, text, e) {
  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;";
  $("body").append("<div class='div-tips' style='" + divtipsstyle + "'>" + text + "</div>");

  var divtips = $(".div-tips");
  divtips.css("visibility", "visible");

  var top = e.clientY + $(window).scrollTop() - divtips.height() - 18;
  var left = e.clientX;
  divtips.css("top", top);
  divtips.css("left", left);

  $(target).mousemove(function (e) {
   var top = e.clientY + $(window).scrollTop() - divtips.height() - 18;
   var left = e.clientX;
   divtips.css("top", top);
   divtips.css("left", left);
  });
 },

 //移除提示
 removetips: function () {
  $(".div-tips").remove();
 }
};

$(function () {
 SimpoValidate.init();
});

 如何使用:

 Edit页面:

@using Model.Suya;
@{
 ViewBag.Title = "Add";
 Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
 List<sys_post> postList = (List<sys_post>)ViewData["postList"];
 sys_post post = (sys_post)ViewData["post"];
}
<script type="text/javascript">
 $(function () {
  //部门树
  $('#dept').combotree({
   url: 'GetDeptTree',
   required: false,
   checkbox: true,
   onLoadSuccess: function () {
    $('#dept').combotree('setValue', "@(post.depCode)");
   }
  });

  //操作结果
  $("#ifrm").load(function (data) {
   var data = eval("(" + $("#ifrm").contents().find("body").html() + ")");
   alert(data.msg);
   if (data.ok) back();
  });

  $("select[name='postLevel']").find("option[value='@(post.postLevel)']").attr("selected", "selected");
 });

 //保存
 function save() {
  if (valid()) {
   $("#frm").submit();
  }
 }

 //验证
 function valid() {
  var dept = $("input[name='dept']");
  if (!dept.val()) {
   SimpoValidate.hilight(dept.parent(), "请选择所属部门");
  } else {
   SimpoValidate.removehilight(dept.parent());
  }

  return SimpoValidate.valid();
 }

 //返回
 function back() {
  parent.$('#ttTab').tabs('select', "岗位管理");
  var tab = parent.$('#ttTab').tabs('getSelected');
  tab.find("iframe").contents().find("#btnSearch").click();
  parent.$("#ttTab").tabs('close', '修改岗位信息');
 }
</script>
<div class="tiao">
 <input type="button" class="submit_btn" value="保存" onclick="save()" />
 <input type="button" class="submit_btn" value="返回" onclick="back()" />
</div>
<iframe id="ifrm" name="ifrm" style="display: none;"></iframe>
<form id="frm" method="post" enctype="multipart/form-data" action="/HR/PostManage/SaveEdit?id=@(post.id)"
target="ifrm">
<div class="adminMainContent">
 <div class="box">
  <div class="box-title">
   基础信息
  </div>
  <div class="box-content">
   <table cellpadding="0" cellspacing="0" class="detail" width="100%">
    <tr>
     <td class="title">
      <span class="mst">*</span>岗位名称:
     </td>
     <td style="width: 35%;">
      <input type="text" class="xinxi_txt" name="postName" value="@post.postName" />
      <span class="valid" msg="必填,且长度不能超过50" rule="^(.|\n){0,50}$"></span>
     </td>
     <td class="title">
      <span class="mst">*</span>岗位编号:
     </td>
     <td style="width: 35%;">
      <input type="text" class="xinxi_txt" name="postCode" value="@post.postCode" />
      <span class="valid" msg="必填,且长度不能超过20" rule="^(.|\n){0,20}$" ajaxaction="/HR/PostManage/AjaxCheckPostCode?id=@post.id">
      </span>
     </td>
    </tr>
    <tr>
     <td class="title">
      <span class="mst">*</span> 所属部门:
     </td>
     <td style="width: 35%;">
      <input type="text" name="depCode" id="dept" class="easyui-combotree" style="height: 30px;" />
     </td>
     <td class="title">
      <span class="mst">*</span>汇报对象:
     </td>
     <td style="width: 35%;">
      <select class="xueli" name="reportPostCode" id="agreementType">
       <option value="" selected="selected">==请选择==</option>
       @foreach (sys_post item in postList)
       {
        if (item.postCode == post.reportPostCode)
        {
        <option value="@item.postCode" selected="selected">@item.postName</option>
        }
        else
        {
        <option value="@item.postCode">@item.postName</option>
        }
       }
      </select>
      <span class="valid" msg="请选择合同分类">
     </td>
    </tr>
    <tr>
     <td class="title">
      <span class="mst">*</span>岗位级别:
     </td>
     <td style="width: 35%;">
      <select class="xueli" name="postLevel">
       <option value="" selected="selected">==请选择==</option>
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
      </select>
      <span class="valid" msg="请选择岗位级别">
     </td>
     <td class="title">
     </td>
     <td style="width: 35%;">
     </td>
    </tr>
    <tr>
     <td class="title">
      <span class="mst">*</span>备注:
     </td>
     <td colspan="3" style="width: 35%;">
      <textarea name="remarks" style="width: 500px;">@post.remarks</textarea>
      <span class="valid" msg="长度不得超过500" rule="^(.|\n){0,500}$"></span>
     </td>
    </tr>
   </table>
  </div>
 </div>
</div>
</form>

效果图:

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

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

Javascript 相关文章推荐
js DOM模型操作
Dec 28 Javascript
url地址自动加#号问题说明
Aug 21 Javascript
node.js中的path.join方法使用说明
Dec 08 Javascript
让html元素随浏览器的大小自适应垂直居中的实现方法
Oct 12 Javascript
jQuery 出现Cannot read property ‘msie’ of undefined错误的解决方法
Nov 23 Javascript
微信小程序 本地存储及登录页面处理实例详解
Jan 11 Javascript
vue2.0中goods选购栏滚动算法的实现代码
May 17 Javascript
webpack4 + react 搭建多页面应用示例
Aug 03 Javascript
js中对象和面向对象与Json介绍
Jan 21 Javascript
详解vue中router-link标签所必备了解的属性
Apr 15 Javascript
JS原型与继承操作示例
May 09 Javascript
jQuery实现可编辑的表格
Dec 11 jQuery
Javascript中prototype属性实现给内置对象添加新的方法
May 14 #Javascript
Javascript进制转换实例分析
May 14 #Javascript
Javascript中For In语句用法实例
May 14 #Javascript
Javascript中With语句用法实例
May 14 #Javascript
javascript用函数实现对象的方法
May 14 #Javascript
javascript中动态函数用法实例分析
May 14 #Javascript
javascript函数特点实例分析
May 14 #Javascript
You might like
PHP中动态HTML的输出技术
2006/10/09 PHP
PHP连接SQLServer2005方法及代码
2013/12/26 PHP
PHP中浮点数计算比较及取整不准确的解决方法
2015/01/09 PHP
yii2安装详细流程
2018/05/23 PHP
javascript中的nextSibling使用陷(da)阱(keng)
2014/05/05 Javascript
Javascript 正则表达式实现为数字添加千位分隔符
2015/03/10 Javascript
举例详解Python中smtplib模块处理电子邮件的使用
2015/06/24 Javascript
JavaScript使用DeviceOne开发实战(二) 生成调试安装包
2015/12/01 Javascript
javascript实现简单计算器效果【推荐】
2016/04/19 Javascript
H5基于iScroll实现下拉刷新和上拉加载更多
2017/07/18 Javascript
基于jquery实现的tab选项卡功能示例【附源码下载】
2019/06/10 jQuery
Weex开发之地图篇的具体使用
2019/10/16 Javascript
Layui弹框中数据表格中可双击选择一条数据的实现
2020/05/06 Javascript
springboot+vue+对接支付宝接口+二维码扫描支付功能(沙箱环境)
2020/10/15 Javascript
原生js 实现表单验证功能
2021/02/08 Javascript
python用ConfigObj读写配置文件的实现代码
2013/03/04 Python
Python中的True,False条件判断实例分析
2015/01/12 Python
python中的break、continue、exit()、pass全面解析
2017/08/05 Python
Python文本特征抽取与向量化算法学习
2017/12/22 Python
pycharm恢复默认设置或者是替换pycharm的解释器实例
2018/10/29 Python
python同时替换多个字符串方法示例
2019/09/17 Python
基于python中__add__函数的用法
2019/11/25 Python
Django对接支付宝实现支付宝充值金币功能示例
2019/12/17 Python
Python通过TensorFLow进行线性模型训练原理与实现方法详解
2020/01/15 Python
解决pyinstaller 打包exe文件太大,用pipenv 缩小exe的问题
2020/07/13 Python
python实现计算器简易版
2020/12/17 Python
Herschel Supply Co.美国:背包、手提袋及配件
2020/11/24 全球购物
C# .NET面试题
2015/11/28 面试题
环境科学专业大学生自荐信格式
2013/09/21 职场文书
三分钟演讲稿事例
2014/03/03 职场文书
党员创先争优承诺书
2014/03/26 职场文书
同学会演讲稿
2019/04/02 职场文书
一篇文章了解正则表达式的替换技巧
2022/02/24 Javascript
TV动画《史上最强大魔王转生为村民A》番宣CM公布
2022/04/01 日漫
《月歌。》宣布制作10周年纪念剧场版《RABBITS KINGDOM THE MOVIE》
2022/04/02 日漫
Smart 2 车辆代号 HC11 全新谍照曝光
2022/04/21 数码科技