常用 表单验证之一 validator.js

介绍了JS表单验证类Validator的使用方法及属性配置,包括常见数据类型的验证规则及自定义验证逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在提交表单时经常会用到一些表单验证,下面介绍一个不错的JS表单验证类 Validator,可以处理一些常用的验证,如判断是否QQ,是否EMAIL等等

<scrīpt>
/*************************************************
Validator v1.03
code by 我佛山人
wfsr@msn.com
*************************************************/
Validator = {
Require : /.+/,
Email : /^/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*$/,
Phone : /^((/(/d{3}/))|(/d{3}/-))?(/(0/d{2,3}/)|0/d{2,3}-)?[1-9]/d{6,7}(/-/d{1,4})?$/,
Mobile : /^((/(/d{3}/))|(/d{3}/-))?13/d{9}$/,
Url : /^http:////[A-Za-z0-9]+/.[A-Za-z0-9]+[//=/?%/-&_~`@[/]/':+!]*([^<>/"/"])*$/,
IdCard : /^/d{15}(/d{2}[A-Za-z0-9])?$/,
Currency : /^/d+(/./d+)?$/,
Number : /^/d+$/,
Zip : /^[1-9]/d{5}$/,
QQ : /^[1-9]/d{4,8}$/,
Integer : /^[-/+]?/d+$/,
Double : /^[-/+]?/d+(/./d+)?$/,
English : /^[A-Za-z]+$/,
Chinese : /^[/u0391-/uFFE5]+$/,
Username : /^[a-z]/w{3,}$/i,
UnSafe : /^(([A-Z]*|[a-z]*|/d*|[-_/~!@#/$%/^&/*/./(/)/[/]/{/}<>/?/////'/"]*)|.{0,5})$|/s/,
IsSafe : function(str){return !this.UnSafe.test(str);},
SafeString : "this.IsSafe(value)",
Limit : "this.limit(value.length,getAttribute('min'), getAttribute('max'))",
LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
Date : "this.IsDate(value, getAttribute('min'), getAttribute('format'))",
Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value",
Range : "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')",
Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))",
Custom : "this.Exec(value, getAttribute('regexp'))",
Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
ErrorItem : [document.forms[0]],
ErrorMessage : ["以下原因导致提交失败:/t/t/t/t"],
Validate : function(theForm, mode){
var ōbj = theForm || event.srcElement;
var count = obj.elements.length;
this.ErrorMessage.length = 1;
this.ErrorItem.length = 1;
this.ErrorItem[0] = obj;
for(var i=0;i<count;i++){
with(obj.elements){
var _dataType = getAttribute("dataType");
if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") continue;
this.ClearState(obj.elements);
if(getAttribute("require") == "false" && value == "") continue;
switch(_dataType){
case "Date" :
case "Repeat" :
case "Range" :
case "Compare" :
case "Custom" :
case "Group" :
case "Limit" :
case "LimitB" :
case "SafeString" :
if(!eval(this[_dataType])) {
this.AddError(i, getAttribute("msg"));
}
break;
default :
if(!this[_dataType].test(value)){
this.AddError(i, getAttribute("msg"));
}
break;
}
}
}
if(this.ErrorMessage.length > 1){
mode = mode || 1;
var errCount = this.ErrorItem.length;
switch(mode){
case 2 :
for(var i=1;i<errCount;i++)
this.ErrorItem.style.color = "red";
case 1 :
alert(this.ErrorMessage.join("/n"));
this.ErrorItem[1].focus();
break;
case 3 :
for(var i=1;i<errCount;i++){
try{
var span = document.createElement("SPAN");
span.id = "__ErrorMessagePanel";
span.style.color = "red";
this.ErrorItem.parentNode.appendChild(span);
span.innerHTML = this.ErrorMessage.replace(//d+:/,"*");
}
catch(e){alert(e.descrīption);}
}
this.ErrorItem[1].focus();
break;
default :
alert(this.ErrorMessage.join("/n"));
break;
}
return false;
}
return true;
},
limit : function(len,min, max){
min = min || 0;
max = max || Number.MAX_VALUE;
return min <= len && len <= max;
},
LenB : function(str){
return str.replace(/[^/x00-/xff]/g,"**").length;
},
ClearState : function(elem){
with(elem){
if(style.color == "red")
style.color = "";
var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
if(lastNode.id == "__ErrorMessagePanel")
parentNode.removeChild(lastNode);
}
},
AddError : function(index, str){
this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
},
Exec : function(op, reg){
return new RegExp(reg,"g").test(op);
},
compare : function(op1,operator,op2){
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2);
}
},
MustChecked : function(name, min, max){
var groups = document.getElementsByName(name);
var hasChecked = 0;
min = min || 1;
max = max || groups.length;
for(var i=groups.length-1;i>=0;i--)
if(groups.checked) hasChecked++;
return min <= hasChecked && hasChecked <= max;
},
IsDate : function(op, formatString){
formatString = formatString || "ymd";
var m, year, month, day;
switch(formatString){
case "ymd" :
m = op.match(new RegExp("^((//d{4})|(//d{2}))([-./])(//d{1,2})//4(//d{1,2})$"));
if(m == null ) return false;
day = m[6];
month = m[5]*1;
year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
break;
case "dmy" :
m = op.match(new RegExp("^(//d{1,2})([-./])(//d{1,2})//2((//d{4})|(//d{2}))$"));
if(m == null ) return false;
day = m[1];
month = m[3]*1;
year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
break;
default :
break;
}
if(!parseInt(month)) return false;
month = month==0 ?12:month;
var date = new Date(year, month-1, day);
return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
}
}
</scrīpt>

 

 

使用:

语法:dataType="Require | Chinese | English | Number | Integer | Double | Email | Url | Phone | Mobile | Currency | Zip | IdCard | QQ | Date | SafeString | Repeat | Compare | Range | Limit | LimitB | Group | Custom"

类型:字符串。必选。
说明:用于设定表单项的输入数据验证类型。
选值说明:
可选值 验证功能
Require 必填项
Chinese 中文
English 英文

Number
数字
Integer
整数
Double
实数
Email
Email地址格式
Url
基于HTTP协议的网址格式
Phone
电话号码格式
Mobile
手机号码格式
Currency
货币格式
Zip
邮政编码
IdCard
身份证号码
QQ
QQ号码
Date
日期
SafeString
安全密码
Repeat
重复输入
Compare
关系比较
Range
输入范围
Limit
限制输入长度
LimitB
限制输入的字节长度
Group 验证单/多选按钮组
Custom 自定义正则表达式验证

 

语法:max="int"
类型:字符串。在dataType属性值为Range时必选,为Group且待验证项是多选按钮组时可选(此时默认值为1),为为Limit/LimitB时可选(此时默认值为1.7976931348623157e+308,即Number.MAX_VALUE的值)。
说明:当daType属性值为Range时,用于判断输入是否在min与max的属性值间;当dataType属性值为Group,且待验证项是多选按钮组时,用于设定多选按钮组的选中个数,判断选中个数是否在[min, max]区间;当daType属性值为Limit时,用于验证输入的字符数是否在[min, max]区间;当daType属性值为LimitB时,用于验证输入字符的字节数是否在[min, max]区间。

 


语法:min="int"
类型:字符串。在dataType属性值为Range时必选,为Group且待验证项是多选按钮组时可选(此时默认值为1),为为Limit/LimitB时可选(此时默认值为0)。
说明:当daType属性值为Range时,用于判断输入是否在min与max的属性值间;当dataType属性值为Group,且待验证项是多选按钮组时,用于设定多选按钮组的选中个数,判断选中个数是否在[min, max]区间;当daType属性值为Limit时,用于验证输入的字符数是否在[min, max]区间;当daType属性值为LimitB时,用于验证输入字符的字节数是否在[min, max]区间。


语法: msg="string"
类型:字符串。必选。
说明:在验证失败时要提示的出错信息。


语法:operator="NotEqual | GreaterThan | GreaterThanEqual | LessThan | LessThanEqual | Equal"
类型:字符串。在dataType属性值为Compare时可选(默认值为Equal)。
说明:参考to属性。
各选值所对应的关系操作符:
可选值 意义说明
NotEqual
不等于 !=
GreaterThan
大于 >
GreaterThanEqual
大于等于 >=
LessThan
小于 <
LessThanEqual
小于等于 <=
Equal 等于 =

 

语法:require="true | false"
类型:字符串。可选。
说明:用于设定表单项的验证方式。当值为false时表单项不是必填项,但当有填写时,仍然要执行dataType属性所设定的验证方法,值为true或任何非false字符时可省略此属性。


语法:to="sting | int"
类型:字符串。当dataType值为Repeat或Compare时必选。
说明:当dataType值为Repeat时,to的值为某表单项的name属性值,用于设定当前表单项的值是否与目标表单项的值一致;当dataType的值为Compare时,to的选值类型为实数,用于判断当前表单项的输入与to的值是否符合operator属性值所指定的关系。


语法:format="ymd | dmy"
类型:字符串。在dataType属性值为Date时可选(默认值为ymd)。
说明:用于验证输入是否为符合format属性值所指定格式的日期。
符合规则的输入示例 : 2004-11-23,2004/11/23,04.11.23,23-11-2004等
注意:当输入的年份为2位时,如果数值小于30,将使年份看作处于21世纪,否则为20世纪。


语法:regexp="object"
类型:字符串。在dataType属性值为Custom时必选。
说明:用于验证输入是否符合regexp属性所指定的正则表达式。


示例:

<scrīpt src="./Js/validator.js"></scrīpt>
<form name="middle_price" action="index.php" method="post" id="middle_price" ōnSubmit="return Validator.Validate(this,3)">
<table width="595" height="244" border="1" align="left" cellpadding="0" cellspacing="1" bgcolor="#C9C9C9">
<tr>
    <th height="15" colspan="2" align="center" bgcolor="#837B6D" class="style1"> </th>
</tr><!--单张印刷报价-->
<tr>
    <td width="153" height="23" align="right">数量(张)</td>
    <td width="448">
   <select name="paper_num" dataType="Require" msg="未选定数量">
      <option value="" selected>请选择</option>
   <option value="200">200</option>
   <option value="500">500</option>
   <option value="1000">1000</option>
   <option value="2000">2000</option>
   <option value="3000">3000</option>
   <option value="5000">5000</option>
   <option value="10000">10000</option>
   <option value="zdy">自定义</option>  
   </select>
</td>
</tr>
<tr>
    <td height="23" align="right">纸张厚度(克)</td>
    <td>
   <select name="paper_thinckness" dataType="Require" msg="未选定纸张厚度">
      <option value="" selected>请选择</option>
   <option value="80">80</option>
   <option value="90">90</option>
   <option value="95">95</option>
   <option value="100">100</option>
   <option value="105">105</option>
   <option value="120">120</option>
   <option value="128">128</option>
   <option value="150">150</option>
   <option value="157">157</option>
   <option value="180">180</option>
   <option value="200">200</option>
   <option value="zdy">自定义</option>
   </select>
</td>
</tr>
<tr>
    <td height="18" align="right">纸张类型</td>
    <td>
   <select name="paper_type" dataType="Require" msg="未选定纸张类型">
      <option value="" selected>请选择</option>
      <option value="特种纸">特种纸</option>
   <option value="单面铜版纸">单面铜版纸</option>
   <option value="双面铜版纸">双面铜版纸</option>
   <option value="哑粉纸">哑粉纸</option>
   <option value="双胶纸(胶版纸)">双胶纸(胶版纸)</option>
   <option value="轻涂纸">轻涂纸</option>
   <option value="新闻纸">新闻纸</option>
   <option value="信封纸 (牛皮纸)">信封纸 (牛皮纸)</option>
   <option value="不干胶">不干胶</option>
       </select>
</td>
</tr>
<tr>
    <td height="18" align="right">纸张尺寸(长X宽/厘米)</td>
    <td>
   长<input name="paper_width" type="text" size="4" width="25" dataType="Double" msg="纸张尺寸-长度,请用数字">
      X宽<input name="paper_height" type="text" size="4" width="25" dataType="Double" msg="纸张尺寸-宽度,请用数字">
      厘米
</td>
</tr>
<tr>
    <td height="16" align="right">印刷颜色</td>
    <td>
   <input type="radio" name="print_color" value="单面(4+0)">单面(4+0)
      <input type="radio" name="print_color" value="双面(4+4)" dataType="Group" msg="必须选择一个印刷颜色">双面(4+4)
</td>
</tr>
<tr>
    <td height="18" align="right">总价(元)</td>
    <td><input type="text" name="price_total" size="10" dataType="Currency" msg="总价请用数字">
      <input type="checkbox" name="show_price" value="1">显示<!--1显示,0 不显示--></td>
</tr>
<tr>
    <td height="18" align="right">备注</td>
    <td><textarea name="notes" cols="30" rows="4"></textarea></td>
</tr>
<tr>
    <td height="15" colspan="2" align="center">
    <input type="submit" name="Submit" value="提交报价">
      </td>
    </tr>
</table>
</form>


示例的一点点说明:

在form 里加 ōnSubmit="return Validator.Validate(this,3)" 其中可以定义三种错误模式,可选1,2,3(次处是3),亲自试先好点!

js-validator 是 Laravel 风格的 JavaScript 对象验证库。使用 js-validator 来验证对象或者 JSON 是否符合规则非常方便,而且具有很好的可扩展性。举个例子var example = {       text: 'Hello world!',       date: '2015-07-07',       comments: null,     },     rules = {       text: 'required|string',       date: 'date|date_format:yyyy-MM-dd',       comments: 'integer',     }; console.log(Validator.validate(example, rules)); // => Object {status: "failed", field: "comments", rule: "integer"}基本用法引入validator.js(原生JavaScript)[removed] [removed]或[removed] [removed]初始化(非原生JavaScript)Node.jsnpm install ppoffice/js-validator --savevar validator = require('js-validator');RequireJSrequirejs(["../src/validator"], function(validator) {   ... });Sea.jsdefine(function (require, exports, module) {   var validator = require('./validator');   ... });制定验证规则对于同一个对象属性,你可以并列制定几个不同的规则进行限定,使用|作为不同规则间的分割符。var rules = {   text: 'required|string',   date: 'date|date_format:yyyy-MM-dd',   comments: 'integer', };验证validator.validate(object_to_be_tested, rules);如果待验证对象符合规则,validate函数返回true;否则返回带有验证状态、失败的属性和对应失败的规则信息的对象。添加验证器使用add方法为Validator添加验证器,第一个参数为验证器名称,第二个参数为验证方法,可以为正则表达式对象或者函数。当验证方法为函数时,其第一个参数必须为当前验证域的值,后面的参数根据需求而定,验证成功时结果返回true。validator.add('older_than', function (value, age) {   return value > age; });var rules = {   age: 'integer|older_than:17', };可用的验证规则验证规则规则含义accepted验证域必须为yes、on、1、或者true。 这个规则常用语验证“同意使用条款”表单。after:date验证的日期域的日期必须在指定日期之后。alpha验证域必须由纯英文字符组成。alpha_dash验证域必须由英文字符、数字、中划线或者下划线组成。alpha_num验证域必须由英文字符或者数字组成。array验证域必须为数组对象。before:date验证的日期域的日期必须在给定日期之前。between:min,max验证域的值必须在min和max之间,验证域可以是数字或者字符串。boolean验证域的值可以看作是布尔值,可以是true,false,1,0,"1","0",'1' and '0'。date验证域必须为日期字符串形式,可以被Date.parse方法解析。date_format:format验证域必须符合制定的日期格式,允许的日期格式参照源代码中的dateFormat方法。different:field验证域的值必须域指定域的值不同。digits:value验证域必须为数字,且其位数为给定的位数。digits_between:min,max验证域必须为数字,且其位数在min和max之间。email验证域必须为电子邮件地址格式。in:foo,bar,...验证域的值必须在给定的允许值列表中。integer验证值必须为整数。ip验证值必须为IP地址形式(支持IPv4与IPv6)。max:value验证域的值必须小于等于max,验证域可以是数字或者字符串。mimes:foo,bar,...验证值的扩展名必须在给定的扩展名列表中。min:value验证域的值必须大于等于min,验证域可以是数字或者字符串。not_in:foo,bar,...验证域的值必须不在给定的值列表中。numeric验证域必须为数字。regex验证域必须符合指定的正则表达式(JavaScript风格)。required验证域必须存在。required_if:field,value,...如果给定的域的值等于给定的值,验证域必须存在。这里的条件可以是多个域和值,它们之间的关系为“与”。required_with:foo,bar,...如果给定的域之中任何一个存在的话,验证域必须存在。required_with_all:foo,bar,...仅当所有给定的域存在时,验证域必须存在。required_without:foo,bar,...如果给定的域之中任何一个不存在的话,验证域必须存在。required_without_all:foo,bar,...仅当所有给定的所有域都不存在时,验证域必须存在。same验证域的值必须域指定域的值相同。size:value验证域的大小必须等于指定大小。对于字符串来说,验证域的字符串长度必须等于给定长度。对于数字来说,验证域的值必须等于给定值。string验证域必须为字符串。url验证域必须为URL地址。当前不支持含有非英文(中文等)字符的地址。测试文件入口./test/index.html     原生JavaScript支持测试./test/node.js        Node.js支持测试./test/requirejs.html RequireJS支持测试./test/seajs.html Sea.js支持测试 标签:jsvalidator
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值