轻松搞定js表单验证_javascript技巧

先看看效果图:

html:

引入

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/Validate-1.0.1.js"></script>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>
  <script src="/Scripts/jquery-1.10.2.js"></script>
  <script src="/Scripts/Validate-1.0.1.js"></script>
  <link href="/Content/system.css" rel="stylesheet" type="text/css" />
  <link href="/Content/metro.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <form id="form1" runat="server">
    <div class="form_content">
      <div class="form_center_part">
        <div class="form_view_main">
          <div class="form_part">
            <table width="100%" border="0" cellspacing="0" cellpadding="0" class="table_part_t">
              <tbody>
                <tr>
                  <th>长度区间:</th>
                  <td class="graytxt1">
                    <asp:TextBox ID="txtNewPwd" runat="server" class="required length_2_5" />
                  </td>
                </tr>
                <tr>
                  <th>必填</th>
                  <td class="graytxt1">
                    <asp:TextBox ID="txtPwd" runat="server" class="required"/>
                  </td>
                </tr>
                <tr>
                  <th>正整数</th>
                  <td class="graytxt1">
                    <asp:TextBox ID="TextBox1" runat="server" class="integer" />
                  </td>
                </tr>
                <tr>
                  <th>小数</th>
                  <td class="graytxt1">
                    <asp:TextBox ID="TextBox3" runat="server" class="decimal" />
                  </td>
                </tr>
                <tr>
                  <th>手机</th>
                  <td class="graytxt1">
                    <asp:TextBox ID="txtMobile" runat="server" class="required mobile"></asp:TextBox>
                  </td>
                </tr>
                <tr>
                  <th>电话</th>
                  <td class="graytxt1">
                    <asp:TextBox ID="TextBox2" runat="server" class="tel"></asp:TextBox>
                  </td>
                </tr>
                <tr>
                  <th>单选</th>
                  <td class="graytxt1">
                    <asp:RadioButtonList ID="rbtnlCode" runat="server" class="rbtn required" RepeatLayout="Flow" RepeatDirection="Horizontal">
                      <asp:ListItem Value="1">无</asp:ListItem>
                      <asp:ListItem Value="2">A</asp:ListItem>
                      <asp:ListItem Value="3">B</asp:ListItem>
                    </asp:RadioButtonList>
                  </td>
                </tr>
                <tr>
                  <th>多选</th>
                  <td class="graytxt1">
                    <asp:CheckBoxList ID="chklCode" runat="server" class="chk required length_2_4" RepeatLayout="Flow" RepeatDirection="Horizontal">
                      <asp:ListItem Value="1">A</asp:ListItem>
                      <asp:ListItem Value="2">B</asp:ListItem>
                      <asp:ListItem Value="3">C</asp:ListItem>
                      <asp:ListItem Value="4">D</asp:ListItem>
                      <asp:ListItem Value="5">E</asp:ListItem>
                    </asp:CheckBoxList>
                    <br />
                    最少选择2项但不超过4项
                  </td>
                </tr>
                <tr>
                  <th>多选111</th>
                  <td class="graytxt1">
                    <asp:CheckBoxList ID="CheckBoxList1" runat="server" class="chk length_2_0" RepeatLayout="Flow" RepeatDirection="Horizontal">
                      <asp:ListItem Value="1">A</asp:ListItem>
                      <asp:ListItem Value="2">B</asp:ListItem>
                      <asp:ListItem Value="3">C</asp:ListItem>
                      <asp:ListItem Value="4">D</asp:ListItem>
                      <asp:ListItem Value="5">E</asp:ListItem>
                    </asp:CheckBoxList>
                    <br />
                    至少选择2项
                  </td>
                </tr>
                <tr>
                  <th>下拉</th>
                  <td class="graytxt1">
                    <asp:DropDownList ID="drpCode" runat="server" class="drp required">
                      <asp:ListItem Value="">请选择</asp:ListItem>
                      <asp:ListItem Value="2">A</asp:ListItem>
                      <asp:ListItem Value="3">B</asp:ListItem>
                    </asp:DropDownList>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="btn_center">
            <asp:Button ID="btnSubmit" runat="server" CssClass="btn_box submit" Text="提交" OnClick="btnSubmit_Click" />
            <asp:Button ID="btnSave" runat="server" CssClass="btn_box save" Text="保存" OnClick="btnSave_Click" />
          </div>
        </div>
      </div>
    </div>
  </form>
</body>
</html>

脚本:Validate-1.0.1.js

/// <reference path="jquery-1.10.2-vsdoc.js" />
/*
  @Name:验证
  @Author:朱翰洲
  @WeChat/QQ:86128281
  @Version: 1.0.1 Beta
  @Update:2016/10/10
  @Desc: 将会持续更新

使用说明:
  1)demo源码为ASP.NET
  2)需要验证的控件加onblur="Check(this)"或onclick="Check(this)"。
  3)Check(),可自定义提示消息,无自定义时读取默认提示,详见该函数内的注释。
  4)页面无其他逻辑验证时,可加入Validate-?.?.?.default.js脚本文件,无需在控件中加入Check(this)。
  5)radio、checkbox和select详见selectClass或Validate()内的注释。
  6)文本、多选有length_?_?区间验证(至少?项)时须与控件ID命名匹配(id^=xx),否则保存时将会跳过该验证,详见SaveValidate()。
  7)若仅需控制MaxLength建议使用MaxLength属性。
  8)常用格式验证(.mobile,.tel,.email)需对应,需要其他验证可扩展。
  9)若有验证格式如手机、电话等格式,将不再验证长度
  10)css文件中的名称不得与该验证中使用的class名称冲突。
  11)所有class可根据使用习惯更改。

class:
  1)required:非空
  2)onerror:标记错误
  3)length_?_?:详见checkLength()内的注释
  4)rbtn:radio
  5)chk:checkbox
  6)drp:select
  7)mobile:手机
  8)tel:电话
  9)email:邮箱

 */

//.rbtn as RadioButtonList
//.chk as CheckBoxList
//.drp as DropDownList
var selectClass = ".rbtn,.chk,.drp";

//获取验证类型class
function getDictTypeClass() {
  var keys = ".";
  $.each(dictType, function (key, val) {
    keys += key + ",.";
  });
  return keys.substring(0, keys.length - 2);
}

var dictType = {
  "mobile": ["手机", /^0?(13[0-9]|15[0-9]|18[0-9]|14[57])[0-9]{8}$/],
  "tel": ["电话", /^0\d{2,3}-?\d{7,8}$/],
  "email": ["邮箱", /^[0-9a-z][0-9a-z\-\_\.]+@([0-9a-z][0-9a-z\-]*\.)+[a-z]{2,}$/i],
  "integer": ["整数", /^[1-9]+[0-9]*]*$/],
  "decimal": ["数字", /^[0-9]+.?[0-9]*$/],
}

$(function () {
  $(".required").each(function () {
    $(this).parent().append("<em>*</em>");//在必填项后添加 * 标记必填,可根据需要修改显示位置
  });
  try {
    //判断是否有Check()
    if (jQuery.isFunction(Check)) {
      $(selectClass).click(function () {
        Check(this);
      });
      $(getDictTypeClass() + ",.required").blur(function () {
        Check(this);
      });
      $("#btnSubmit").click(function () {
        return SubmitValidate();
      })
      $("#btnSave").click(function () {
        return SaveValidate();
      })
    }
  }
  catch (err) {

  }
});

function Check(par, message) {
  var id = getId(par.id);
  if (typeof (message) == "undefined") {
    //未设置message 读取默认提示信息
    message = ($(id).is(selectClass) ? "请选择" : "请输入") + $(id).parent().prev().text().trim().replace(':', '').replace(':', '');
  }
  Validate(id, message);
}

//验证
function Validate(id, message) {
  var isRequired = getIsRequired(id);
  if ($(id).is(selectClass)) {
    $(id).css("background", "none");
    //单选
    if ($(id).hasClass("rbtn")) {
      if (isRequired) {
        if (typeof ($("input:radio[name='" + replaceId(id) + "']:checked").val()) == "undefined") {
          AddError(id, message);
        } else {
          RemoveError(id);
        }
      }
    }
      //多选
    else if ($(id).hasClass("chk")) {
      var options = $("input[name^='" + replaceId(id) + "']:checked").length;//选项(数量)
      var isLength = getIsCheckLength(id);//有选项限制
      if (isLength || isRequired) {
        //必选
        if (isRequired) {
          if (options > 0) {
            //有选择项限制
            if (isLength == true) {
              checkLength(id, options, "");
              //return;
            }
            else {
              RemoveError(id);
            }
          } else {
            AddError(id, message);//未选中
          }
        }
          //非必选,但选择后有选择项限制
        else if (isLength && options > 0) {
          checkLength(id, options, "");
        }
        else {
          RemoveError(id);
        }
      }
    }
      //下拉
    else if ($(id).hasClass("drp")) {
      if (isRequired) {
        if ($(id).val() == "") {
          AddError(id, message);
        } else {
          RemoveError(id);
        }
      }
    }
  }
    //TextBox
  else {
    if ($(id).val().trim() !== "") {
      if (getIsCheckLength(id)) {
        checkLength(id, $(id).val().trim().length, "text");
      }
      else {
        checkFormat(id); //格式验证不再验证长度
      }
    } else {
      if (isRequired) {
        AddError(id, message);
      } else {
        RemoveError(id);
      }
    }
  }
}
//是否必填
function getIsRequired(id) {
  return $(id).hasClass("required");
}
//是否验证长度
function getIsCheckLength(id) {
  if (typeof ($(id).attr('class')) != "undefined") {
    return $(id).attr('class').indexOf('length') != "-1";
  } else {
    return "false";
  }
}
//验证长度 itemLength长度或选项数量。text文本其他值为多选
function checkLength(id, itemLength, text) {
  //$(id).filter(":contains('length')")
  if (getIsCheckLength(id)) {
    var length = getClassName(id, "length");
    var min = length.split('_')[1], max = length.split('_')[2];//取出最小值和最大值
    //min为0时,取max的最大长度
    if (min == 0) {
      var tips = text == "text" ? "最大长度不超过" + max + "位字符" : "需选择" + max + "项";
      if (itemLength > max) {
        AddError(id, tips);
      }
      else {
        RemoveError(id);
      }
    }
      //max为0时,取min的最小长度
    else if (max == 0) {
      if (itemLength < min) {
        AddError(id, text == "text" ? "请输入" + (min - 1) + "位以上字符" : "至少选择" + min + "项");
      }
      else {
        RemoveError(id);
      }
    }
      //min和max大于0时,取区间
    else if (min > 0 && max > 0) {
      var tips = text == "text" ? "请输入" + min + "~" + max + "位的字符" : "需选择" + +min + "~" + max + "项";
      if (itemLength < min) {
        AddError(id, tips);
      }
      else if (itemLength > max) {
        AddError(id, tips);
      }
      else {
        RemoveError(id);
      }
    }
    else {
      RemoveError(id);
    }
  }
}

String.prototype.trim = function () {
  return this.replace(/(^\s*)|(\s*$)/g, '');
};
var error_icon = "<img src=/Images/error_small.png>";
//验证失败,添加onerror
function AddError(id, message) {
  var spId = id.replace("#", "sp");
  $(id).addClass("onerror");
  if ($(id).nextAll("span") == undefined || $(id).nextAll("span").attr("id") !== spId) {
    if ($(id).next().html() === "*") {// 提示信息放在必填验证符号后
      $(id).next().after("<span id='" + spId + "' style='color:red'>" + error_icon + message + "</span>");
    } else {
      $(id).after("<span id='" + spId + "' style='color:red'>" + error_icon + message + "</span>");
    }
  } else {
    $("#" + spId).html(error_icon + message);
  }
}
//验证成功,移除onerror
function RemoveError(id) {
  $(id).removeClass("onerror");
  $(id.replace("#", "#sp")).html("");
}
//删除ID中的#(参数id:#txtId)
function replaceId(id) {
  return id.replace("#", "");
}
//在ID前加上#(参数id:txtId)
function getId(id) {
  return "#" + id;
}
//判断className是否存在,返回className
function getClassName(id, className) {
  var clazzs = $(id).attr('class');// 获取class 字符串
  var classIndex = clazzs.substring(clazzs.indexOf(className));//截取
  if (classIndex != "-1") {
    var last = classIndex.indexOf(" ");//判断后面是否有空格或其他样式
    return (last == -1 ? classIndex : classIndex.substring(0, last));
  }
  return "";
}
//验证格式(验证内容详见dictType)
function checkFormat(id) {
  if ($(id).is(getDictTypeClass()) && $(id).val().trim() != "") {
    var clazz = getDictTypeClass().replace('.', '').split(',');
    for (var i = 0; i < clazz.length; i++) {
      if ($(id).attr('class').indexOf(clazz[i].replace('.', '')) != "-1") {
        var name = clazz[i].replace('.', '');
        if (dictType[name][1].exec($(id).val().trim())) {
          RemoveError(id)
        }
        else {
          AddError(id, dictType[name][0] + "格式错误");
        }
        break;
      }
    }
  }
  else {
    RemoveError(id);
  }
}

//提交时验证
function SubmitValidate() {
  $(".required:input").trigger('blur');
  $(selectClass).trigger('click');
  return $(".onerror").length == 0;
}
//保存时验证
function SaveValidate() {
  $(".onerror").each(function () {
    RemoveError(getId($(this).attr("id")));//移除所有验证的提示
  });
  //查找所有需要验证格式的文本,若非空,验证格式是否正确
  $(getDictTypeClass()).each(function () {
    if ($(this).val().trim() != "") {
      checkFormat(getId($(this).attr("id")));
    }
  });
  //验证区间
  $("form [id^=txt],[id^=chk]").each(function () {
    var id = $(this).attr('id');
    //文本框
    if (id.indexOf("txt") != "-1") {
      if ($(this).val().trim() != "" && getIsCheckLength(getId(id))) {
        checkLength(getId(id), $(this).val().trim().length, "text");
      }
    }
      //多选
    else {
      var options = $("input[name^='" + id + "']:checked").length;
      if (options > 0 && getIsCheckLength(getId(id))) {
        checkLength(getId(id), options, "");
      }
    }
  });
  return $(".onerror").length == 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索js
表单验证
轻松搞定extjs、轻松搞定高中数学、轻轻松松搞定高考、韩顺平轻松搞定网页、轻松搞定网页设计笔记,以便于您获取更多的相关知识。

时间: 2024-08-16 11:26:26

轻松搞定js表单验证_javascript技巧的相关文章

js浏览器html5表单验证_javascript技巧

html5表单添加了很多类型的表单,而且还自带验证的功能.在移动端,手机等设备能够根据不同的input类型弹出不同的键盘,例如iphone弹的键盘 但是由于不同的浏览器对不合法输入提示文案不一致,样式也不一样,并且老的浏览器不兼容(IE9及以下),导致了在生产环境中比较少见到.例如对于邮箱格式的检验,不同浏览器的效果如下: Chrome Firefox IE safari html5的表单跨浏览器有很大的问题 具体来说存在三个问题: (1) 输入框blur的时候不会触发检查,只有在点提交时才触发

分享纯手写漂亮的表单验证_javascript技巧

哈哈 手工馒头好吃,今天小编跟大家分享手工js表单验证代码,感兴趣的朋友快来吧. 因为是自定义样式,所以兼容所有浏览器版本,个人认为非常漂亮:网址wuxi.rongzi.com css <style> /*tooltip*//* CSS属性顺序按照 字母首字母 排列*/ .ui-slider-tooltip{ background:#fa; border:px solid #fa; color:#fff; display: block; text-align: left; padding: p

javascript制作的简单注册模块表单验证_javascript技巧

一个注册框  进行表单验证处理 如图 有简单的验证提示功能 代码思路也比较简单 输入框失去焦点时便检测,并进行处理 表单具有 onsubmit = "return check()"行为,处理验证情况 点击提交表单按钮时,进行最终的验证,达到是否通过表单提交的请求. 先是最基本的html+css部分 <style type="text/css"> body{margin:0;padding: 0;} .login{position:relative;mar

JavaScript实现仿网易通行证表单验证_javascript技巧

介绍一下表单验证,不错哦: 如图 CSS代码 @charset "gb2312"; /* CSS Document */ body,dl,dt,dd,div,form {padding:0;margin:0;} #header,#main{ width:650px; margin:0 auto; } .bg{ background-image:url(../images/register_bg.gif); background-repeat:no-repeat; width:6px;

javascript实现的简单的表单验证_javascript技巧

表单验证几乎是不可缺少的,有的表单验证是在后台完成的,有的则是使用JavaScript在在前端完成基本的验证,这样可以有效的减轻服务器的压力,下面就介绍一下JS实现的最简单的表单验证.代码实例如下: <!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title></title> <script type="text/javascript&q

Bootstrap Validator 表单验证_javascript技巧

在线演示地址:http://www.shouce.ren/study/api/s/jq--BootstrapValidator--index.html 使用方法,代码如下所示: 1.<form id="defaultForm" method="post" class="form-horizontal" action="target.php"> 2. <div class="form-group&qu

javascript html5实现表单验证_javascript技巧

表单验证为终端用户检测无效的数据并标记这些错误,是一种用户体验的优化. 下面展现浏览器自带的验证功能也可在移动端中查看: HTML部分: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-sc

javascript实现表单验证_javascript技巧

本文实例讲解了javascript实现表单验证的详细代码,分享给大家供大家参考,具体内容如下 效果图: 具体代码: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <script type="text/j

JS实现支持Ajax验证的表单插件_javascript技巧

本文为大家分享了一个表单验证插件,支持ajax验证,使用起来很简单. 每个需要验证的表单元素下面有一个span标签,这个标签的class有一个valid表示需要验证,如果有nullable则表示可为空:rule表示验证规则,msg表示错误提示信息:to表示要验证的元素的name值,如果元素是单个的,to可以不写.该插件会遍历每个有valid的span标签,找出它前面需要验证的元素,根据rule验证,如果验证不通过,则显示边框为红色,鼠标放在元素上时显示错误信息. 验证时机:1.点击提交按钮时显式