添加標籤屬性就搞定的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;],//phone:[&quot;0?1(345789)[09]9&quot;,&quot;&quot;],//mobile:[&quot;[1][09]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}",“請輸入正確的手機號碼”], //以一開頭的11位數字
telephone : ["^([0-9]{3,4}-)?[0-9]{7,8}&quot;,&quot;&quot;],//postalCode:[&quot;[19][09]5&quot;,&quot;座機號碼格式錯誤&quot;], //校驗座機 postalCode : [&quot;^[1-9][0-9]{5}",“郵編格式錯誤”], //驗證郵編
number : ["^-?\d+&quot;,&quot;&quot;],//zNum:[&quot;[09]&quot;,&quot;只能爲數字&quot;], //數字 zNum : [&quot;^[0-9]*",“只能爲正整數”], //正整數
twoDec : ["^-?[0-9]+(\.[0-9]{1,2})?&quot;,&quot;&quot;],//areacode:[&quot;0[09]2,3&quot;,&quot;最多保留兩位小數&quot;], //最多保留兩位小數 areacode : [&quot;^0[0-9]{2,3}",“區號格式錯誤”], //區號
lgzNum : ["1[1-9][0-9]&quot;,&quot;&quot;],//&gt;0enCode:[&quot;[AZaz]+&quot;,&quot;只能爲大於零的數字&quot;], // &gt;0的正整數 enCode : [&quot;^[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,&quot;&quot;],//year:[&quot;(194919[59][09]20[09][09]21[09][09])/g,&quot;只能英文字母或數字&quot;],//只能英文字母或數字 year : [&quot;^(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-/])+&quot;,&quot;httpshttp&quot;],//fax:[&quot;([09]3,4)?[09]7,8&quot;,&quot;必須以https或http開頭&quot;],//網址 fax : [&quot;^([0-9]{3,4}-)?[0-9]{7,8}",“請輸入正確的傳真號碼”]//傳真

代碼中有 大家也可以對其進行添加修改!


  1. 0-9 ↩︎

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

  3. A-Za-z0-9 ↩︎

  4. 0-9 ↩︎

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章