前言:这个基于query的表单校验js文件是我18年写的,当时开发一个政府项目,技术算是老旧。后来换了公司,vue这些当下流行的框架用上之后,在我的观念里,jQuery纯粹dom操作的时代过去了,之前写的东西已经过时,所以弃之。
然而万万没想到,两年内几经周折,再一次进了一家传统的与政府合作的公司,技术老旧不是,连公用的常用的功能都没有封装,纯粹代码堆砌,完成功能就行,这让我整夜辗转反侧,为自己的未来担忧。
我的事情就说到这里,下面介绍一下一个简单实用的js小框架(jqv)-----jquery表单校验器,致力于傻瓜式开发!
老规矩先看一下效果:
实例代码如下:
详细说明:
不管是input还是select标签,我们只需要将需要校验的这些标签通过这个validForm注册后即可(这个方法的id是这些标签的父级,可看代码,如果一个页面多个表单,我们可传一个id数组)。
我们只需要在标签上加上required就是必填校验 如果用户点击后焦点离开就会在后面又红色提示语,如果用户没有填写过,在点击提交的时候,触发了submitValid方法,也会提示并定位到提示的标签上。
而validForm、submitValid是这个js框架提供的方法,也是被用到的两个方法,用好这两个方法,可以校验所有你想校验的表单!
特殊校验,如图中手机号校验,我们只需要在标签上添加validType="phone"即可它与required可以同时存在,也可单独存在,至于validType的值,我们js文件里面有,一些常用的正则校验已经收录,如果不满足你可以对其进行修改添加(不需要读代码就能修改)
注意:submitValid的用法,它有第二个参数submitValid('ss',1),如果我们在提交是时候没有传第二个参数(只要为真即可,我一般传1),它是不会校验必填项的,只会校验那些特殊的,如果特殊校验通过的话,默认校验通过!
使用方法三步:1,引入js校验文件;2,在校验的标签上加校验属性;3,表单提交的时候调用一下校验方法即可!
以下是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]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/","最多保留两位小数"], //最多保留两位小数
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$","身份证号格式错误"],//身份证
mail : ["^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$","邮箱格式错误"],//Email
date : ["^\d{4}-\d{2}-\d{2}$","日期格式错误"],//日期 yyyy-mm-dd
bankId : ["^[0-9]{16}|[0-9]{19}$","银行卡号格式错误"], //银行卡号
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|ftp|rtsp|mms){0,1}(:\/\/){0,1})www\.(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$","请输入正确的网址"],//网址
fax : ["^([0-9]{3,4}-)?[0-9]{7,8}$","请输入正确的传真号码"]//传真
},
//触发事件
triggerEvent:function(self){
if($(self).is(":hidden")){
$(self).parent().find(".msg-y").remove();
}else{
$(self).trigger("blur");
}
},
//验证方法
vf:function(e){
//拿到特殊的验证标签
var validType = $(this).attr("validType");
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 ($.trim(val) == "") {
var errorMsg = "不能为空!";
if(validType === undefined){
$parent.append("<span class='msg-y onError'>" + errorMsg + "</span>");
}else{
$parent.append("<span class='msg-y onErrorT'>" + errorMsg + "</span>");
}
}else{
var smg = customValidform.regExpVaild(validType,val);
if(smg) {
$parent.append("<span class='msg-y onErrorT'>"+smg+"</span>")
}else{
$parent.find(".msg-y").remove();
};
}
},
//防止事件执行完后,浏览器自动为标签获得焦点
th:function(){
$(this).triggerHandler("blur");
},
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]").unbind(".a").bind({"blur.a":customValidform.vf,"keyup.a":customValidform.th});
$("#" + id + " [required]").each(function(){
if($(this).prop("type") == "radio" || $(this).prop("type") == "checkbox"){
$(this).unbind(".a").bind({"blur.a":customValidform.vf,"click.a":customValidform.vf})
$(this).siblings("input").unbind(".a").bind({"blur.a":customValidform.vf,"click.a":customValidform.vf});
}else{
$(this).unbind(".a").bind({"blur.a":customValidform.vf,"keyup.a":customValidform.vf})
}
});
}
};
// 提交验证
function submitValid(id,all) {
// trigger 事件执行完后,浏览器会为submit按钮获得焦点
var errorLables = [];
if(all){
$("#" + id + " [required],#" + id + " [validType]").each(function(){
customValidform.triggerEvent(this);
});
errorLables = $("#" + id + " .msg-y");
}else{
$("#" + id + " [validType]").each(function(){
customValidform.triggerEvent(this);
})
errorLables = $("#" + id + " .onErrorT");
}
// 未填字段获得焦点
if (errorLables.length > 0)
$(errorLables[0]).prev().focus();
if(errorLables.length==0){
return true;
}else{
return false;
}
}
//表单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);