阿尔法数据验证(2013版)
一、概述:
这个版本数据过滤插件和之前几个版本的最大区别是验证改为了链式的写法。
验证插件的核心思想是这个样子的,他是把提交页面整个的巡检一遍,提取有validate标签的控件然后绑定一堆事件在上面,当输入控件的值发生变化,或者鼠标经过都会去出发验证事件
二、使用说明:
1、引用文件:
<script src="../Scripts/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="../Scripts/validate-2.0.1.js" type="text/javascript"></script>
<link href="../App_Themes/Spring/Css.css" rel="stylesheet" type="text/css" />
<link href="../App_Themes/Spring/Validation.css" rel="stylesheet" type="text/css" />
2、各种验证格式:
序号 |
验证类型 |
格式 |
1 |
必填项 |
validate="{required:true}" |
2 |
最小长度 |
validate="{minlength:5}" |
3 |
最大长度 |
validate="{mexlength:5}" |
4 |
邮件格式 |
validate="{datatype:'email'}" |
5 |
数字格式 |
validate="{datatype:'digital'}" |
6 |
日期格式 |
validate="{datatype:'date'}" |
7 |
正整数格式 |
validate="{datatype:'pinteger'}" |
8 |
URL格式 |
validate="{datatype:'url'}" |
9 |
小数格式 |
validate="{datatype:'float',num:3}" |
10 |
格式字符 |
validate="{datatype:'special'}" |
11 |
中文 |
validate="{datatype:'chinese'}" |
12 |
英文 |
validate="{datatype:'english'}" |
13 |
最大值 |
validate="{maxvalue:100}" |
14 |
最小值 |
validate="{minvalue:10}" |
15 |
身份证 |
validate="{datatype:'idcard'}" |
16 |
|
validate="{datatype:'qq'}" |
17 |
phone |
validate="{datatype:'phone'}" |
18 |
mobile |
validate="{datatype:'mobile'}" |
注意:
a) 以上验证格式可以组合验证,比如可以验证必填的同时验证为邮件格式validate="{required:true,datatype:’email’}"等组合验证,
b) 如果要自定义提示信息也可以,msg:’你的提示信息’, validate="{msg:’你的提示信息’}",
c) 验证小数的时候num是用来控制小数位数的,默认为2位小数
d) 提交服务器的时候只需验证 validate(‘table01’) 即可,table01为需要验证的那个区域的table编号;如果页面上有多个table,而用户只需验证某一个table 则只需要填写那个table的id几个,不用整个页面都验证
三、附源码
Javascript代码如下:
/* Created by Euler 2013.7 Email:404115630@qq.com Version:2.0.0 history: 1、验证格式改为链式方便书写、便于阅读 */ $(document).ready(function () { _initvalidateClass(); }); (function ($) { var validateClass = { parameters: { "message": { "required": "\u5FC5\u586B\u9879", //必填项 "minlength": "\u6700\u5C0F\u957F\u5EA6", //最小长度 "mexlength": "\u6700\u5927\u957F\u5EA6", //最大长度 "char": "\u5B57\u7B26", //字符 "email": "\u4E3AEmail\u683C\u5F0F", //为Email格式 "digital": "\u4E3A\u6570\u5B57\u683C\u5F0F", //为数字格式 "date": "\u4E3A\u65E5\u671F\u683C\u5F0F", //为日期格式 "zipcode": "\u4E3A\u90AE\u7F16\u683C\u5F0F", //为邮编格式 "pinteger": "\u4E3A\u6B63\u6574\u6570", //为正整数 "url": "\u4E3AUrl\u683C\u5F0F", //为 Url 格式 "float": "\u4E3A\u5C0F\u6570", //为小数 "photo": "\u4E3A\u56FE\u7247\u683C\u5F0F", //为图片格式 "special": "\u542B\u6709\u7279\u6B8A\u5B57\u7B26", //含有特殊字符 "chinese": "\u4E3A\u4E2D\u6587", //为中文 "english": "\u4E3A\u82F1\u6587", //为英文 "maxvalue": "\u6700\u5927\u503C\u4E3A", //最大值为 "minvalue": "\u6700\u5C0F\u503C\u70BA", //最小值为 "idcard": "\u4E3A\u8EAB\u4EFD\u8BC1\u683C\u5F0F", "repeat": "\u8F93\u5165\u4E0D\u4E00\u6837", //两次输入不一样 "qq": "\u8BF7\u8F93\u5165\u6B63\u786E\u7684QQ\u53F7", //请输入正确的QQ号 "phone": "\u8BF7\u8F93\u5165\u6B63\u786E\u7684\u7535\u8BDD\u53F7\u7801", //请输入正确的电话号码 "mobile": "\u8BF7\u8F93\u5165\u6B63\u786E\u7684\u624B\u673A\u53F7"//请输入正确的手机号 }, "defaults": { msg: '', required: false, datatype: '', minlength: 0, mexlength: 0, maxvalue: 0, minvalue: 0, num: 2 } }, operateStr: { _getLen: function (val) { var cArr = val.match(/[^\x00-\xff]/ig); return val.length + (cArr == null ? 0 : cArr.length); }, _getAttr: function (obj, attr) { var _validate = $(obj).attr("validate"); var obj = eval("(" + _validate + ")"); var op = $.extend(true, {}, validateClass.parameters.defaults, obj); return $(op).attr(attr) }, msg: function (obj, val) { var msg = val; if (validateClass.operateStr._getAttr(obj, 'msg')) { msg = validateClass.operateStr._getAttr(obj, 'msg'); } var tip = $("<div class=\"validatebox-tip\">" + "<span class=\"validatebox-tip-content\">" + msg + "</span>" + "<span class=\"validatebox-tip-pointer\">" + "</span>" + "</div>").insertAfter(obj); //insertAfter 追加到要验证元素的后面 tip.css({ display: "block", left: $(obj).offset().left + $(obj).outerWidth(), top: $(obj).offset().top }); }, replace: function (val_raw, val_Find, val_Replace) { var tmpval = val_raw.toString(); return tmpval.split(val_Find).join(val_Replace); }, getDate: function () { var Current_Date = new Date(); var Current_Month = Current_Date.getMonth() + 1; var Current_year = Current_Date.getYear(); var Current_day = Current_Date.getDate(); return Current_year + "-" + Current_Month + "-" + Current_day; }, valid: function (obj) { var validStr = "#" + obj; if (obj == null || obj == "" || typeof (obj) == "undefined") { validStr = "form"; } $(validStr).find("input[validate]:visible,textarea[validate]:visible").each(function () { if (validateClass.operateStr._getAttr(this, 'required')); { $(this).trigger('blur'); } }); $(".validatebox-tip").each(function () { $(this).show(); }) var numError = $(validStr).find(".validatebox-tip").length; if (numError) { return false; } return true; } , _initvalidate: function () { $("input[validate]:visible,textarea[validate]:visible").each(function () { if (validateClass.operateStr._getAttr(this, 'required') && !$(this).hasClass('Wdate')) { $(this).addClass("validatebox-invalid"); } }); $("input[validate]:visible,textarea[validate]:visible").bind("blur", function () { var $parent = $(this).parent(); $parent.find(".validatebox-tip").remove(); var val = $.trim(this.value).split("'").join("-"); val = val.split("\\").join("-"); var msge = ""; msge = validateClass.parameters.message['required']; var _required = validateClass.operateStr._getAttr(this, 'required'); if (_required != undefined && _required != -1 && _required) { if (null == val || "" == val) { validateClass.operateStr.msg(this, msge); return; } } var _minlength = validateClass.operateStr._getAttr(this, 'minlength'); if (_minlength != undefined && _minlength != 0 && _minlength) { msge = validateClass.parameters.message['minlength'] + _minlength + validateClass.parameters.message['char']; if (validateClass.operateStr._getLen(val) < _minlength) { validateClass.operateStr.msg(this, msge); return; } } var _mexlength = validateClass.operateStr._getAttr(this, 'mexlength'); if (_mexlength != undefined && _mexlength !=0 && _mexlength) { msge = validateClass.parameters.message['mexlength'] + _mexlength + validateClass.parameters.message['char']; if (validateClass.operateStr._getLen(val) > _mexlength) { validateClass.operateStr.msg(this, msge); return; } } var ischeck = "true"; var _datatype = validateClass.operateStr._getAttr(this, 'datatype') if (_datatype) { if (null == val || "" == val) { return; } var formart = _datatype; msge = validateClass.parameters.message[formart]; switch (formart) { case "email": ischeck = "validateClass.validStr.isEmail('" + val + "')"; break; case "digital": ischeck = "validateClass.validStr.isDigital('" + val + "')"; break; case "date": ischeck = "validateClass.validStr.isDate('" + val + "')"; break; case "zipcode": ischeck = "validateClass.validStr.isZipCode('" + val + "')"; break; case "pinteger": ischeck = "validateClass.validStr.isInt('" + val + "')"; break; case "url": ischeck = "validateClass.validStr.isUrl('" + val + "')"; break; case "float": var tcount = 2; var _num = validateClass.operateStr._getAttr(this, 'num') if (_num) { tcount = _num; } ischeck = "validateClass.validStr.isFloat('" + val + "'," + tcount + ")"; break; case "special": ischeck = "validateClass.validStr.isSpecial('" + val + "')"; break; case "chinese": ischeck = "validateClass.validStr.isChinese('" + val + "')"; break; case "english": ischeck = "validateClass.validStr.isEnglish('" + val + "')"; break; case "idcard": ischeck = "validateClass.validStr.isIdCard('" + val + "')"; break; case "qq": ischeck = "validateClass.validStr.isQQ('" + val + "')"; break; case "phone": ischeck = "validateClass.validStr.isPhone('" + val + "')"; break; case "mobile": ischeck = "validateClass.validStr.isMobile('" + val + "')"; break; } if (!eval(ischeck)) { validateClass.operateStr.msg(this, msge); return; } } var _maxvalue = validateClass.operateStr._getAttr(this, 'maxvalue'); if (_maxvalue != undefined && _maxvalue != 0) { msge = validateClass.parameters.message["maxvalue"] + _maxvalue; if (parseFloat(val) > _maxvalue) { validateClass.operateStr.msg(this, msge); return; } } var _minvalue = validateClass.operateStr._getAttr(this, 'minvalue'); if (_minvalue != undefined && _minvalue != 0) { msge = validateClass.parameters.message["minvalue"] + _minvalue; if (parseFloat(val) < _minvalue) { validateClass.operateStr.msg(this, msge); return; } } }).keyup(function () { $(this).triggerHandler("blur"); }).focus(function () { $(this).triggerHandler("blur"); }).mouseover(function () { $(this).triggerHandler("blur"); }).change(function () { $(this).triggerHandler("blur"); }); } }, validStr: { isEmail: function (val) { if (val.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true; else return false; }, isInt: function (val) { var reg = /^[0-9]*[1-9][0-9]*$/; return val.match(reg); }, isDate: function (val) { var datestr = val.split('/').join('-'); datestr = datestr.split(':').join('-'); datestr = datestr.split('.').join('-'); if (datestr.split('-')[0].length == 2) { var current = new Date(); var current_year = current.getFullYear(); datestr = current_year.toString().substring(0, 2) + datestr; } var dateFormart = /^(\d{4})(-)(\d{1,2})(-)(\d{1,2})$/; var matchArr = datestr.match(dateFormart); if (null == matchArr) { return false; } month = matchArr[3]; day = matchArr[5]; year = matchArr[1]; if (month < 1 || month > 12) { return false; } if (day < 1 || day > 31) { return false; } if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) { return false; } if (month == 2) { var isleap = (year / 4 == 0 && (year / 100 != 0 || year / 400 == 0)); if (day > 29) { return false; } if (day == 29 && !isleap) { return false; } } return true; }, isZipCode: function (val) { var reg = /^[1-9]\d{5}$/; return reg.test(val); }, isFloat: function (val, fcout) { var reg = /^(-?\d+)(\.\d+)?$/; if (reg.test(val)) { if (val.indexOf(".") != -1 && val.length - (val.indexOf(".") + 1) > fcout) { return false; } else { return true; } } else { return false; } }, isPhoto: function (strPhoto, strFormat) { if (strPhoto.indexOf(".") > -1) { var point = strPhoto.lastIndexOf("."); var file = strPhoto.substring(point + 1, strPhoto.length); if (!(strFormat.indexOf(file.toLowerCase()) > -1)) { return false; } else { return true; } } else { return false; } }, isSpecial: function (val) { for (var i = 0; i < val.length; i++) { var ch = val.charAt(i); if ((ch == "`") || (ch == "~") || (ch == "!") || (ch == "@") || (ch == "#") || (ch == "\"") || (ch == "^") || (ch == "&") || (ch == "*") || (ch == "(") || (ch == ")") || (ch == "+") || (ch == "=") || (ch == "|") || (ch == "{") || (ch == "}") || (ch == "[") || (ch == "]") || (ch == ":") || (ch == ";") || (ch == "'") || (ch == '"') || (ch == "<") || (ch == ">") || (ch == ",") || (ch == ".") || (ch == "\\") || (ch == "?") || (ch == "/")) { return false; } } return true; }, isDigital: function (val) { var reg = /^(-)?\d+(?=\.{0,1}\d+$|$)/ return reg.test(val) }, isUrl: function (val) { var reg = /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/; return val.match(reg); }, isChinese: function (val) { var reg = /^[\u0391-\uFFE5]+$/; return val.match(reg); }, isEnglish: function (val) { var reg = /^[A-Za-z]+$/; return val.match(reg); }, isIdCard: function (val) { var date, Ai; var verify = "10x98765432"; var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; var area = ['', '', '', '', '', '', '', '', '', '', '', '北京', '天津', '河北', '山西', '内蒙古', '', '', '', '', '', '辽宁', '吉林', '黑龙江', '', '', '', '', '', '', '', '上海', '江苏', '浙江', '安微', '福建', '江西', '山东', '', '', '', '河南', '湖北', '湖南', '广东', '广西', '海南', '', '', '', '重庆', '四川', '贵州', '云南', '西藏', '', '', '', '', '', '', '陕西', '甘肃', '青海', '宁夏', '新疆', '', '', '', '', '', '台湾', '', '', '', '', '', '', '', '', '', '香港', '澳门', '', '', '', '', '', '', '', '', '国外']; var re = val.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i); if (re == null) return false; if (re[1] >= area.length || area[re[1]] == "") return false; if (re[2].length == 12) { Ai = val.substr(0, 17); date = [re[9], re[10], re[11]].join("-"); } else { Ai = val.substr(0, 6) + "19" + val.substr(6); date = ["19" + re[4], re[5], re[6]].join("-"); } //if (!isDate(date)) return false;取消生日的验证 var sum = 0; for (var i = 0; i <= 16; i++) { sum += Ai.charAt(i) * Wi[i]; } Ai += verify.charAt(sum % 11); return (val.length == 15 || val.length == 18 && val == Ai); }, isRepeat: function (val, valb) { return val == valb; }, isQQ: function (val) { var reg = /^[1-9]\d{4,8}$/; return val.match(reg); }, isPhone: function (val) { var reg = /^(([0\+]\d{2,3})?(0\d{2,3}))?(\d{7,8})((\d{3,}))?$/; return val.match(reg); }, isMobile: function (val) { var reg = /^((\(0\d{2,3}\))|(\d{3}\-))?13|5\d{9}$/; return val.match(reg); } } }; $.fn.validate = function (obj) { return validateClass.operateStr.valid(obj); }; validate = function (obj) { return validateClass.operateStr.valid(obj); }; _initvalidateClass = function () { validateClass.operateStr._initvalidate(); }; })(jQuery);
HTML源码如下:
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script src="../Scripts/jquery-1.10.1.min.js" type="text/javascript"></script> <script src="../Scripts/validate-2.0.1.js" type="text/javascript"></script> <link href="../App_Themes/Spring/Css.css" rel="stylesheet" type="text/css" /> <link href="../App_Themes/Spring/Validation.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <table id="table01" class="Tab"> <tr> <td colspan="2" class="Title"> 各种验证Demo: </td> </tr> <tr> <th style="width: 30%"> 必填项: </th> <td> <asp:TextBox ID="txtchar" runat="server" CssClass="Input" validate="{required:true}"></asp:TextBox> </td> </tr> <tr> <th> 最小长度: </th> <td> <asp:TextBox ID="TextBox1" runat="server" CssClass="Input" validate="{minlength:5}"></asp:TextBox> </td> </tr> <tr> <th> 最大长度: </th> <td> <asp:TextBox ID="TextBox2" runat="server" CssClass="Input" validate="{mexlength:5}"></asp:TextBox> </td> </tr> <tr> <th> 邮件格式: </th> <td> <asp:TextBox ID="TextBox3" runat="server" CssClass="Input" validate="{datatype:'email'}"></asp:TextBox> </td> </tr> <tr> <th> 数字格式: </th> <td> <asp:TextBox ID="TextBox4" runat="server" CssClass="Input" validate="{datatype:'digital'}"></asp:TextBox> </td> </tr> <tr> <th> 日期格式: </th> <td> <asp:TextBox ID="TextBox5" runat="server" CssClass="Input" validate="{datatype:'date'}"></asp:TextBox> </td> </tr> <tr> <th> 正整数格式: </th> <td> <asp:TextBox ID="TextBox6" runat="server" CssClass="Input" validate="{datatype:'pinteger'}"></asp:TextBox> </td> </tr> <tr> <th> URL格式: </th> <td> <asp:TextBox ID="TextBox7" runat="server" CssClass="Input" validate="{datatype:'url'}"></asp:TextBox> </td> </tr> <tr> <th> 小数格式,默认2位小数,num可以控制小数的位数: </th> <td> <asp:TextBox ID="TextBox8" runat="server" CssClass="Input" validate="{datatype:'float',num:3}"></asp:TextBox> </td> </tr> <tr> <th> 特殊字符: </th> <td> <asp:TextBox ID="TextBox9" runat="server" CssClass="Input" validate="{datatype:'special'}"></asp:TextBox> </td> </tr> <tr> <th> 中文: </th> <td> <asp:TextBox ID="TextBox10" runat="server" CssClass="Input" validate="{datatype:'chinese'}"></asp:TextBox> </td> </tr> <tr> <th> 英文: </th> <td> <asp:TextBox ID="TextBox11" runat="server" CssClass="Input" validate="{datatype:'english'}"></asp:TextBox> </td> </tr> <tr> <th> 最大值: </th> <td> <asp:TextBox ID="TextBox12" runat="server" CssClass="Input" validate="{maxvalue:100}"></asp:TextBox> </td> </tr> <tr> <th> 最小值: </th> <td> <asp:TextBox ID="TextBox13" runat="server" CssClass="Input" validate="{minvalue:10}"></asp:TextBox> </td> </tr> <tr> <th> 身份证: </th> <td> <asp:TextBox ID="TextBox14" runat="server" CssClass="Input" validate="{datatype:'idcard'}"></asp:TextBox> </td> </tr> <tr> <th> QQ: </th> <td> <asp:TextBox ID="TextBox15" runat="server" CssClass="Input" validate="{datatype:'qq'}"></asp:TextBox> </td> </tr> <tr> <th> phone: </th> <td> <asp:TextBox ID="TextBox16" runat="server" CssClass="Input" validate="{datatype:'phone'}"></asp:TextBox> </td> </tr> <tr> <th> mobile: </th> <td> <asp:TextBox ID="TextBox17" runat="server" CssClass="Input" validate="{datatype:'mobile'}"></asp:TextBox> </td> </tr> <tr> <th> </th> <td> <asp:Button ID="btntest" runat="server" Text="Test" OnClientClick="return validate('table01');" /> </td> </tr> </table> </form> </body> </html>