添加标签属性就搞定的js表单校验(基于jquery)

使用步骤:

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]+ &quot; , &quot; 只 能 为 中 文 &quot; ] , / / 验 证 中 文 p h o n e : [ &quot; 0 ? 1 ( 3 ∣ 4 ∣ 5 ∣ 7 ∣ 8 ∣ 9 ) [ 0 − 9 ] 9 &quot; , &quot; 手 机 号 码 格 式 错 误 &quot; ] , / / 验 证 手 机 号 m o b i l e : [ &quot; [ 1 ] [ 0 − 9 ] 10 &quot;,&quot;只能为中文&quot;], //验证中文 phone : [&quot;0?1(3|4|5|7|8|9)[0-9]{9}&quot;,&quot;手机号码格式错误&quot;],//验证手机号 mobile : [&quot;^[1][0-9]{10} ",""],//phone:["0?1(345789)[09]9",""],//mobile:["[1][09]10",“请输入正确的手机号码”], //以一开头的11位数字
telephone : ["^([0-9]{3,4}-)?[0-9]{7,8} &quot; , &quot; 座 机 号 码 格 式 错 误 &quot; ] , / / 校 验 座 机 p o s t a l C o d e : [ &quot; [ 1 − 9 ] [ 0 − 9 ] 5 &quot;,&quot;座机号码格式错误&quot;], //校验座机 postalCode : [&quot;^[1-9][0-9]{5} ",""],//postalCode:["[19][09]5",“邮编格式错误”], //验证邮编
number : ["^-?\d+ &quot; , &quot; 只 能 为 数 字 &quot; ] , / / 数 字 z N u m : [ &quot; [ 0 − 9 ] ∗ &quot;,&quot;只能为数字&quot;], //数字 zNum : [&quot;^[0-9]* ",""],//zNum:["[09]",“只能为正整数”], //正整数
twoDec : ["^-?[0-9]+(\.[0-9]{1,2})? &quot; , &quot; 最 多 保 留 两 位 小 数 &quot; ] , / / 最 多 保 留 两 位 小 数 a r e a c o d e : [ &quot; 0 [ 0 − 9 ] 2 , 3 &quot;,&quot;最多保留两位小数&quot;], //最多保留两位小数 areacode : [&quot;^0[0-9]{2,3} ",""],//areacode:["0[09]2,3",“区号格式错误”], //区号
lgzNum : ["1[1-9][0-9] &quot; , &quot; 只 能 为 大 于 零 的 数 字 &quot; ] , / / &gt; 0 的 正 整 数 e n C o d e : [ &quot; [ A − Z a − z ] + &quot;,&quot;只能为大于零的数字&quot;], // &gt;0的正整数 enCode : [&quot;^[A-Za-z]+ ",""],//>0enCode:["[AZaz]+",“只能为英文”], //英文字母
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 , &quot; 只 能 英 文 字 母 或 数 字 &quot; ] , / / 只 能 英 文 字 母 或 数 字 y e a r : [ &quot; ( 1949 ∣ 19 [ 5 − 9 ] [ 0 − 9 ] ∣ 20 [ 0 − 9 ] [ 0 − 9 ] ∣ 21 [ 0 − 9 ] [ 0 − 9 ] ) /g,&quot;只能英文字母或数字&quot;],//只能英文字母或数字 year : [&quot;^(1949|19[5-9][0-9]|20[0-9][0-9]|21[0-9][0-9]) /g,""],//year:["(194919[59][09]20[09][09]21[09][09])",“请输入正确的年份”],//年份格式
website : ["^((https|http){0,1}(?/){0,1})(([A-Za-z0-9-]+).)+([A-Za-z0-9-/])+ &quot; , &quot; 必 须 以 h t t p s 或 h t t p 开 头 &quot; ] , / / 网 址 f a x : [ &quot; ( [ 0 − 9 ] 3 , 4 − ) ? [ 0 − 9 ] 7 , 8 &quot;,&quot;必须以https或http开头&quot;],//网址 fax : [&quot;^([0-9]{3,4}-)?[0-9]{7,8} ","httpshttp"],//fax:["([09]3,4)?[09]7,8",“请输入正确的传真号码”]//传真

代码中有 大家也可以对其进行添加修改!


  1. 0-9 ↩︎

  2. @A-Za-z0-9!#$%^&*.~ ↩︎

  3. A-Za-z0-9 ↩︎

  4. 0-9 ↩︎

  5. 0-9a-zA-Z ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值