使用步骤:
1、首先新建一个js ,将一下代码复制进去,然后在需要校验的页面中引入。
/*
* required 必填字段 并为字段添加*号标识 例:<input required>
* validType="phone" 手机校验 例:<input validType="phone">
*
* 标签属性加完后 调用 validForm(formids)方法即可
* formids 为id数组
* */
var customValidform = {
regExp:{
chinese : ["^[^u4E00-u9FA5]+$","只能为中文"], //验证中文
phone : ["0?1(3|4|5|7|8|9)[0-9]{9}","手机号码格式错误"],//验证手机号
mobile : ["^[1][0-9]{10}$","请输入正确的手机号码"], //以一开头的11位数字
telephone : ["^([0-9]{3,4}-)?[0-9]{7,8}$","座机号码格式错误"], //校验座机
postalCode : ["^[1-9][0-9]{5}$","邮编格式错误"], //验证邮编
number : ["^-?\d+$","只能为数字"], //数字
zNum : ["^[0-9]*$","只能为正整数"], //正整数
twoDec : ["^-?[0-9]+(\\.[0-9]{1,2})?$","最多保留两位小数"], //最多保留两位小数
areacode : ["^0[0-9]{2,3}$","区号格式错误"], //区号
lgzNum : ["^[0-9]*[1-9][0-9]*$","只能为大于零的数字"], // >0的正整数
enCode : ["^[A-Za-z]+$","只能为英文"], //英文字母
pwd : ["^[\@A-Za-z0-9\!\#\$\%\^\&\*\.\~]{5,18}$","长度在5-18位"],//长度在5-18之间
IDCardNo : ["(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)","身份证号格式错误"],//身份证
mail : ["^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*@([A-Za-z0-9]+[-.])+[A-Za-z0-9]{2,4}$","邮箱格式错误"],//Email
date : ["^\\d{4}-\\d{2}-\\d{2}$","日期格式错误"],//日期 yyyy-mm-dd
bankId : ["^[0-9]{16}|[0-9]{19}|[0-9]{22}$","银行卡号格式错误"], //银行卡号
specialChar : ["[`~!@#$^&%*()=|{}':;\",\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]","只能为特殊字符"],
userName : ["^\w*[A-Za-z\u2E80-\u9FFF]+\w*$","名字不能包含数字或特殊字符"], // 不能是纯数字、可包含中文字符
userNameN : ["^[A-Za-z0-9\u2E80-\u9FFF_()\\[\\]+$","不能含有特殊字符"], // 不包含特殊字符
seat : [/^[0-9a-zA-Z]+$/g,"只能英文字母或数字"],//只能英文字母或数字
year : ["^(1949|19[5-9][0-9]|20[0-9][0-9]|21[0-9][0-9])$","请输入正确的年份"],//年份格式
website : ["^((https|http){0,1}(:\/\/){0,1})(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$","必须以https或http开头"],//网址
fax : ["^([0-9]{3,4}-)?[0-9]{7,8}$","请输入正确的传真号码"]//传真
},
//触发事件
triggerEvent:function(self){
if($(self).is(":hidden") || $(self).is(":disabled")){
$(self).parent().find(".msg-y").remove();
}else{
$(self).trigger("blur");
}
},
//验证方法
vf:function(e){
//拿到特殊的验证标签
var validType = $(this).attr("validType");
var v_len = $(this).attr("length") || 25;
var val = this.value;
// 注意:这里的this是DOM对象,$(this)才是jQuery对象
var $parent = $(this).parent();
// 删除之前的错误提醒信息
$parent.find(".msg-y").remove();
var _type = $(this).prop("type");
if(_type == "radio" || _type == "checkbox"){
var len = $(this).siblings("input:checked").length;
if($(this).is(":checked") || e.type == "click") len++;
if(len>0){
$parent.find(".msg-y").remove();
}else{
if($(this).siblings(".msg-y").length>0){
return;
}else{
$parent.append("<span class='msg-y onError'>必选字段!</span>");
return;
}
}
}
if(validType===undefined){
if ($.trim(val) == "" ) {
$parent.append("<span class='msg-y onError'>不能为空</span>");
}
}else{
if ($.trim(val) != "" ) {
var smg = customValidform.regExpVaild(validType,val);
if(smg) {
$parent.append("<span class='msg-y onErrorT'>"+smg+"</span>")
}else{
$parent.find(".msg-y").remove();
};
}else{
$parent.append("<span class='msg-y onError'></span>");
}
}
if(val.length>v_len){
$parent.find(".msg-y").remove();
$parent.append("<span class='msg-y onErrorT'>字段太长!</span>");
}
},
regExpVaild:function(name,value){
if(name){
var exp = new RegExp(customValidform.regExp[name][0]);
if(!exp.test(value)) return customValidform.regExp[name][1];
}
},
// 失去焦点时 获得焦点 按键松开 验证格式是否正确
blurFrom:function (id) {
$("#" + id + " [validType]").off(".a").on("keyup.a blur.a",customValidform.vf);
$("#" + id + " [required]").off(".a").on("keyup.a blur.a",customValidform.vf);
},
};
// 提交验证
function submitValid(id,all) {
// trigger 事件执行完后,浏览器会为submit按钮获得焦点
var allLables = [];
if(all){
$("#" + id + " [required],#" + id + " [validType]").each(function(){
customValidform.triggerEvent(this);
});
allLables = $("#" + id + " .msg-y");
}else{
$("#" + id + " [validType]").each(function(){
customValidform.triggerEvent(this);
})
allLables = $("#" + id + " .onErrorT");
}
// 未填字段获得焦点
if (allLables.length > 0){
$(allLables[0]).prev().focus();
return false;
}
return true;
}
//表单id 可传数组
function validForm(formids) {
if(Object.prototype.toString.call(formids)=="[object String]"){
customValidform.blurFrom(formids);
}else if(Object.prototype.toString.call(formids)=="[object Array]"){
// 为表单的必填文本框添加提示信息()选择form中的所有后代input元素)
for (var i = 0; i < formids.length; i++) {
// 为表单的必填文本框添加相关事件(blur、focus、keyup)
customValidform.blurFrom(formids[i]);
}
};
}
var nod = document.createElement('style'),
str = '.int {height: 30px;text-align: left;width: 600px;}'
str += ' .high {color: red;} .msg-y {font-size: 13px;} .onError {color: red;} .onErrorT {color: red;}';
nod.type='text/css';
if (nod.styleSheet) { //ie下
nod.styleSheet.cssText = str;
} else {
nod.innerHTML = str; //或者写成 nod.appendChild(document.createTextNode(str))
}
document.getElementsByTagName('head')[0].appendChild(nod);
2、通过表单id将校验事件注册进去,在页面加载完成之后调用此方法即可:validForm(id),其中id也可以是数组。
3、在表单提交时调用submitValid(id),其中id也可以是数组.此方法会校验所有表单项并将不正确的表单提示出来。
使用说明:
required 必填字段 例:
validType=“phone” 手机校验 例:
其他校验字段:
chinese : ["[u4E00-u9FA5]+
"
,
"
只
能
为
中
文
"
]
,
/
/
验
证
中
文
p
h
o
n
e
:
[
"
0
?
1
(
3
∣
4
∣
5
∣
7
∣
8
∣
9
)
[
0
−
9
]
9
"
,
"
手
机
号
码
格
式
错
误
"
]
,
/
/
验
证
手
机
号
m
o
b
i
l
e
:
[
"
[
1
]
[
0
−
9
]
10
","只能为中文"], //验证中文 phone : ["0?1(3|4|5|7|8|9)[0-9]{9}","手机号码格式错误"],//验证手机号 mobile : ["^[1][0-9]{10}
","只能为中文"],//验证中文phone:["0?1(3∣4∣5∣7∣8∣9)[0−9]9","手机号码格式错误"],//验证手机号mobile:["[1][0−9]10",“请输入正确的手机号码”], //以一开头的11位数字
telephone : ["^([0-9]{3,4}-)?[0-9]{7,8}
"
,
"
座
机
号
码
格
式
错
误
"
]
,
/
/
校
验
座
机
p
o
s
t
a
l
C
o
d
e
:
[
"
[
1
−
9
]
[
0
−
9
]
5
","座机号码格式错误"], //校验座机 postalCode : ["^[1-9][0-9]{5}
","座机号码格式错误"],//校验座机postalCode:["[1−9][0−9]5",“邮编格式错误”], //验证邮编
number : ["^-?\d+
"
,
"
只
能
为
数
字
"
]
,
/
/
数
字
z
N
u
m
:
[
"
[
0
−
9
]
∗
","只能为数字"], //数字 zNum : ["^[0-9]*
","只能为数字"],//数字zNum:["[0−9]∗",“只能为正整数”], //正整数
twoDec : ["^-?[0-9]+(\.[0-9]{1,2})?
"
,
"
最
多
保
留
两
位
小
数
"
]
,
/
/
最
多
保
留
两
位
小
数
a
r
e
a
c
o
d
e
:
[
"
0
[
0
−
9
]
2
,
3
","最多保留两位小数"], //最多保留两位小数 areacode : ["^0[0-9]{2,3}
","最多保留两位小数"],//最多保留两位小数areacode:["0[0−9]2,3",“区号格式错误”], //区号
lgzNum : ["1[1-9][0-9]
"
,
"
只
能
为
大
于
零
的
数
字
"
]
,
/
/
>
0
的
正
整
数
e
n
C
o
d
e
:
[
"
[
A
−
Z
a
−
z
]
+
","只能为大于零的数字"], // >0的正整数 enCode : ["^[A-Za-z]+
","只能为大于零的数字"],//>0的正整数enCode:["[A−Za−z]+",“只能为英文”], //英文字母
pwd : ["2{5,18}KaTeX parse error: Got function '\newline' with no arguments as superscript at position 53: … IDCardNo : ["(^̲\\d{15})|(^\d{18}KaTeX parse error: Got function '\newline' with no arguments as superscript at position 4: )|(^̲\\d{17}(\\d|X|x…)",“身份证号格式错误”],//身份证
mail : ["3+([-_.][A-Za-z0-9]+)@([A-Za-z0-9]+[-.])+[A-Za-z0-9]{2,4}KaTeX parse error: Got function '\newline' with no arguments as superscript at position 42: … date : ["^̲\\d{4}-\\d{2}-\…",“日期格式错误”],//日期 yyyy-mm-dd
bankId : ["4{16}|[0-9]{19}|[0-9]{22}KaTeX parse error: Expected 'EOF', got '#' at position 56: …lChar : ["[`~!@#̲^&%()=|{}’:;",\[\].<>/?~!@#¥……&()——|{}【】‘;:”“’。,、?]",“只能为特殊字符”],
userName : ["^\w[A-Za-z\u2E80-\u9FFF]+\w*KaTeX parse error: Can't use function '\u' in math mode at position 76: …: ["^[A-Za-z0-9\̲u̲2E80-\u9FFF_()\…",“不能含有特殊字符”], // 不包含特殊字符
seat : [/5+
/
g
,
"
只
能
英
文
字
母
或
数
字
"
]
,
/
/
只
能
英
文
字
母
或
数
字
y
e
a
r
:
[
"
(
1949
∣
19
[
5
−
9
]
[
0
−
9
]
∣
20
[
0
−
9
]
[
0
−
9
]
∣
21
[
0
−
9
]
[
0
−
9
]
)
/g,"只能英文字母或数字"],//只能英文字母或数字 year : ["^(1949|19[5-9][0-9]|20[0-9][0-9]|21[0-9][0-9])
/g,"只能英文字母或数字"],//只能英文字母或数字year:["(1949∣19[5−9][0−9]∣20[0−9][0−9]∣21[0−9][0−9])",“请输入正确的年份”],//年份格式
website : ["^((https|http){0,1}(?/){0,1})(([A-Za-z0-9-]+).)+([A-Za-z0-9-/])+
"
,
"
必
须
以
h
t
t
p
s
或
h
t
t
p
开
头
"
]
,
/
/
网
址
f
a
x
:
[
"
(
[
0
−
9
]
3
,
4
−
)
?
[
0
−
9
]
7
,
8
","必须以https或http开头"],//网址 fax : ["^([0-9]{3,4}-)?[0-9]{7,8}
","必须以https或http开头"],//网址fax:["([0−9]3,4−)?[0−9]7,8",“请输入正确的传真号码”]//传真
代码中有 大家也可以对其进行添加修改!