js驗證模型自我實現


市面上有很多表單驗證的框架,教我們怎么驗證表單的數據提交,說實話也真的很簡單,但是我們會有一種感覺我們要是離開了這些框架的時候,我們有時候會束手無策,然后js驗證寫的很不規范,沒有一套比較好的模式,那我寫這篇的目的就是:我們自己構建js驗證應該是什么樣子的,來慢慢看一下。
假設我們現在寫一個登錄的頁面(這可能是最簡單的數據提交了哦),html頁面會有一個用戶名和一個密碼的文本框讓我們用戶輸入自己的用戶名和密碼,我們肯定是要判斷用戶名和密碼是否為空,很明顯這樣的js驗證判斷是放在onblur事件里面觸發,html代碼如下:

View Code
< li >
             < label  for ="email" >
                用戶名:
             </ label >
             < input  name ="email"  type ="text"  id ="email"  maxlength ="50"  onblur ="return ValidateHelper.validateStringValueIsEmpty($(this),'通過','不能為空');"   />< em ></ em >
         </ li >
         < li >
             < label  for ="setPwd" >
                密碼:
             </ label >
             < input  name ="setPwd"  type ="password"  id ="setPwd"  maxlength ="16"  onblur ="return ValidateHelper.validateStringValueIsEmpty($(this),'通過','不能為空');"   />< em ></ em >
         </ li >

ValidateHelper是一個對象,一些驗證的方法就是在這個對象里面,我們規定一下,js驗證用戶的輸入有兩返回結果,一個成功,一個是失敗。成功的時候我們輸出成功的提示,

失敗的時候我們輸出失敗的提示,對應的兩個輸出方法:

View Code
    normalMessage:  function(jqueryObj, msg) {
         var emObj = $(jqueryObj.parent().find('em')[0]);
        emObj.empty().append(msg);
    },
    warningMessage:  function(jqueryObj, msg) {
        ValidateHelper.clearMessage(jqueryObj);
         var emObj = $(jqueryObj.parent().find('em')[0]);
         var spanElement = "<span style='color:#FF4C31;float:left;height:23px;line-height:23px;padding:0 10px 0 35px;'>"
                + msg
                + "</span>";
        emObj.empty().append(spanElement);

    },

還有一個清除提示的方法:

View Code
clearMessage:  function(jqueryObj) {
     var emObj = $(jqueryObj.parent().find('em')[0]);
    emObj.empty();
},

我們已經寫了成功和失敗提示方法,以及清除提示的方法,這個三個是我們在后面會一直調用的基本方法。

好了,我們寫一個驗證用戶輸入不能為空的方法:

View Code
    validateStringValueIsEmpty:  function(obj, normalMsg, warningMsg) {
         var jqueryObj = $(obj);
        ValidateHelper.clearMessage(obj);
         if ($.trim(jqueryObj.val()).length == 0) {
            ValidateHelper.warningMessage(jqueryObj, warningMsg);
             return  false;
        }
         else {
            ValidateHelper.normalMessage(jqueryObj, normalMsg);
             return  true;
        }
    },

這個方法會在onblur中被調用的驗證方法,里面自然也用到了成功和失敗提示方法,以及清除提示的方法。參數有三個,要驗證的Dom或者jQuery對象、成功提示信息、失敗提示信

息。要是為空就失敗,要是不為空就成功。

上面寫好的方法在onblur中會觸發的,我們提交數據的時候還會用到得哦:

View Code
    initInfo:  function() {

         var userName = $('#email');
         var userPwd = $('#setPwd');
         if (!ValidateHelper.validateStringValueIsEmpty(userName, '通過', '不能為空')) {
            userName.focus();
             return  null;
        }
         if (!ValidateHelper.validateStringValueIsEmpty(userPwd, '通過', '不能為空')) {
            userPwd.focus();
             return  null;
        }

         var userInfo = {
            UserName: userName.val(),
            UserPwd: userPwd.val()
        };

         return userInfo;
    },

    post:  function() {

         var userInfo = ValidateHelper.initInfo();
         if (userInfo ==  null) {
             return;
        }

        $.ajax({
            type: "post",
            dataType: "text",
            url: "Ajax/Module.aspx",
            timeout: 30000,
            data: { UserName: userInfo.UserName, UserPwd: userInfo.UserPwd },
            success:  function(data) {
                alert(data.toString());
            }
        });
    }

這邊呢要是在提交數據的時候會調用validateStringValueIsEmpty方法,要是返回的是失敗 是不會真的提交給服務器端得。

那上面的情況是一個最簡單的處理不為空的情況,要是我們想驗證是否是Email 是否是身份證號碼,這些復雜的驗證實現如下:

 

var Validation = {
    textCount:  function(field, counter, maxLimit) {
         var message = $(field).val();
         if ($(field).val().length > maxLimit)
            $(field).val(message.substring(0, maxLimit))
         // $(counter).text(maxLimit-field.value.length);     
    },
    refreshValidator:  function(img, input) {
        $(img).attr('src', $(img).attr('src') + "&r=" + Math.random());
        $(input).focus();
    },
    isUrl:  function(s) {
         var strRegex =
                            /^((http(s)?|ftp|telnet|news|rtsp|mms):\/\/)?(((\w(\-*\w)*\.)+[a-zA-Z]{2,4})|(((1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).){3}(1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).?))(:\d{0,5})?(\/+.*)*$/;
         return strRegex.test(s);
    },
    isDecimal:  function(d) {  var pattern = /^(([1-9]\d{0,12})|0)(\.\d{1,2})?$/;  return pattern.test(d); },
    isEmail:  function(s) {
         var pattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
         return pattern.test(s);
    },
    isLowEmail:  function(s) {
         var b, e;
        b = s.indexOf("@");
        e = s.indexOf(".");
         if (b <= 0)  return  false;
         if (e < 0 || e == (s.length - 1)) {  return  false; }
         return  true;
    },
    clearNoNum:  function(event, obj) {
        event = window.event || event;
         if (event.keyCode == 37 | event.keyCode == 39) {
             return;
        }
        obj.value = obj.value.replace(/[^\d.]/g, "");
        obj.value = obj.value.replace(/^\./g, "");
        obj.value = obj.value.replace(/\.{2,}/g, ".");
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    },
    checkNum:  function(obj) {
        obj.value = obj.value.replace(/\.$/g, "");
    },
    isInteger:  function(value) {
         var integerReg =  new RegExp(/^\d+$/);
         return integerReg.test(value);
    },
    isValidateReg:  function(value) {
         var validateReg = /^([A-Za-z0-9\s\-\_\~\!\@\#\$\%\^\&\*\(\)\|\<\>\?\:\;\"\'\.\[\]\{\}\,\+\`\/\\\=]){6,16}$/;
         if (validateReg.test(value)) {
             return  true;
        }
         return  false;
    },
    isDate:  function(strValue) {
         var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/

         if (!objRegExp.test(strValue))
             return  false;
         else {
             var arrayDate = strValue.split(RegExp.$1);
             var intDay = parseInt(arrayDate[2], 10);
             var intYear = parseInt(arrayDate[0], 10);
             var intMonth = parseInt(arrayDate[1], 10);
             if (intMonth > 12 || intMonth < 1) {
                 return  false;
            }
             var arrayLookup = { '1': 31, '3': 31, '4': 30, '5': 31, '6': 30, '7': 31,
                '8': 31, '9': 30, '10': 31, '11': 30, '12': 31
            }
             if (arrayLookup[parseInt(arrayDate[1])] !=  null) {
                 if (intDay <= arrayLookup[parseInt(arrayDate[1])] && intDay != 0)
                     return  true;
            }
             if (intMonth - 2 == 0) {
                 var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
                 if (((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <= 28)) && intDay != 0)
                     return  true;
            }
        }
         return  false;
    },
    isZip:  function(value) {
         var validateReg = /^[0-9]{6}$/;
         return validateReg.test(value);
    },
    checkSpecialChar:  function(value) {
         var validateReg = /([~!@#$%^&*\/\\,.\(\)]){6,16}$/;
         return validateReg.test(value);
    },
    CheckSpecialString:  function(value) {
         var validateReg = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/;
         return validateReg.test(value);
    },
    isTel:  function(s) {
         var patrn = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/
         if (!patrn.exec(s))  return  false
         return  true
    },

    isMobile:  function(value) {
         var validateReg = /^1\d{10}$/;
         return validateReg.test(value);
    },
    getLength:  function(value) {
         return value.replace(/[^\x00-\xff]/g, "**").length;
    },
    isLicence:  function(value) {
         var validateReg = /^[A-Za-z]{10}[0-9]{10}$/;
         return validateReg.test(value);
    },
    isPersonalCard:  function(value) {
         var validateReg = /(^\d{15}$)|(^\d{17}(\d|[A-Za-z]{1})$)/;
         return validateReg.test(value);
    },
    isOrganizationCodeCard:  function(value) {
         var validateReg = /^[A-Za-z0-9]{9}$/;
         return validateReg.test(value);
    },
    isBankAccount:  function(value) {
         var validateReg = /^[1-9]{1}[0-9]*$/;
         return validateReg.test(value);
    },
    MaxLength:  function(field, maxlimit) {
         var j = field.value.replace(/[^\x00-\xff]/g, "**").length;
         var tempString = field.value;
         var tt = "";
         if (j > maxlimit) {
             for ( var i = 0; i < maxlimit; i++) {
                 if (tt.replace(/[^\x00-\xff]/g, "**").length < maxlimit)
                    tt = tempString.substr(0, i + 1);
                 else
                     break;
            }
             if (tt.replace(/[^\x00-\xff]/g, "**").length > maxlimit) {
                tt = tt.substr(0, tt.length - 1);
                field.value = tt;
            }
             else {
                field.value = tt;
            }
        }
    }
};

 

這個類是寫了一些驗證Email 、身份證號碼等等的正則表達式,供我們后面使用,使用方法如下:

    validateStringValueForEmail:  function(obj, normalMsg, warningMsg) {
         var jqueryObj = $(obj);
        ValidateHelper.clearMessage(obj);
         if (!ValidateHelper.validateStringValueIsEmpty(jqueryObj, "通過", "不能為空")) {
            ValidateHelper.warningMessage(jqueryObj, "不能為空");
             return  false;
        }
         if (!Validation.isEmail(jqueryObj.val())) {
            ValidateHelper.warningMessage(jqueryObj, warningMsg);
             return  false;
        }
         else {
            ValidateHelper.normalMessage(jqueryObj, normalMsg);
             return  true;
        }
    },
    validateStringValueForCardID:  function(obj, normalMsg, warningMsg) {
         var jqueryObj = $(obj);
        ValidateHelper.clearMessage(obj);
         if (!ValidateHelper.validateStringValueIsEmpty(jqueryObj, "通過", "不能為空")) {
            ValidateHelper.warningMessage(jqueryObj, "不能為空");
             return  false;
        }
         if (!Validation.isPersonalCard(jqueryObj.val())) {
            ValidateHelper.warningMessage(jqueryObj, warningMsg);
             return  false;
        }
         else {
            ValidateHelper.normalMessage(jqueryObj, normalMsg);
             return  true;
        }
    },

 

那到這邊是基本可以處理我們的一般的js驗證了,可以試試以后用在自己的框架上,我們把自己調試的源碼附上:
ASPX :

View Code
<%@ Page Language= " C# " AutoEventWireup= " true " CodeBehind= " Default.aspx.cs " Inherits= " FormValidateModuleEx._Default " %>

<!DOCTYPE html PUBLIC  " -//W3C//DTD XHTML 1.0 Transitional//EN "  " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= " http://www.w3.org/1999/xhtml ">
<head runat= " server ">
    <title></title>

    <script src= " js\jquery-1.6.2.min.js " type= " text/javascript "></script>
    <script src= " js\MyValidate.js " type= " text/javascript "></script>
    <%--<script src= " js\CheckPersonCardID.js " type= " text/javascript "></script>--%>
</head>
<body>
    <div>
        <li>
            <label  for= " email ">
                用戶名:
            </label>
            <input name= " email " type= " text " id= " email " maxlength= " 50 " onblur= " return ValidateHelper.validateStringValueIsEmpty($(this),'通過','不能為空'); " /><em></em>
        </li>
        <li>
            <label  for= " setPwd ">
                密碼:
            </label>
            <input name= " setPwd " type= " password " id= " setPwd " maxlength= " 16 " onblur= " return ValidateHelper.validateStringValueIsEmpty($(this),'通過','不能為空'); " /><em></em>
        </li>
        <li>
            <label  for= " setPwd ">
                身份證:
            </label>
            <input name= " cardId " type= " text " id= " cardId " onblur= " return ValidateHelper.validateStringValueForCardID($(this),'通過','身份證格式不正確'); " /><em></em><%--IdCardValidate($( this), ' 身份證的格式不正確 ');--%>
        </li>
        <li>
            <label  for= " setPwd ">
                Email:
            </label>
            <input name= " againEmail " type= " text " id= " againEmail " onblur= " return ValidateHelper.validateStringValueForEmail($(this),'通過','email格式不正確'); " /><em></em>
        </li>
        <li><input onclick= " return ValidateHelper.post(); " type= " button " id= " btnPost " /></li>  
    </div>
</body>
</html>

js:

View Code
var Validation = {
    textCount:  function(field, counter, maxLimit) {
         var message = $(field).val();
         if ($(field).val().length > maxLimit)
            $(field).val(message.substring(0, maxLimit))
         // $(counter).text(maxLimit-field.value.length);     
    },
    refreshValidator:  function(img, input) {
        $(img).attr('src', $(img).attr('src') + "&r=" + Math.random());
        $(input).focus();
    },
    isUrl:  function(s) {
         var strRegex =
                            /^((http(s)?|ftp|telnet|news|rtsp|mms):\/\/)?(((\w(\-*\w)*\.)+[a-zA-Z]{2,4})|(((1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).){3}(1\d\d|2([0-4]\d|5[0-5])|[1-9]\d|\d).?))(:\d{0,5})?(\/+.*)*$/;
         return strRegex.test(s);
    },
    isDecimal:  function(d) {  var pattern = /^(([1-9]\d{0,12})|0)(\.\d{1,2})?$/;  return pattern.test(d); },
    isEmail:  function(s) {
         var pattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
         return pattern.test(s);
    },
    isLowEmail:  function(s) {
         var b, e;
        b = s.indexOf("@");
        e = s.indexOf(".");
         if (b <= 0)  return  false;
         if (e < 0 || e == (s.length - 1)) {  return  false; }
         return  true;
    },
    clearNoNum:  function(event, obj) {
        event = window.event || event;
         if (event.keyCode == 37 | event.keyCode == 39) {
             return;
        }
        obj.value = obj.value.replace(/[^\d.]/g, "");
        obj.value = obj.value.replace(/^\./g, "");
        obj.value = obj.value.replace(/\.{2,}/g, ".");
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    },
    checkNum:  function(obj) {
        obj.value = obj.value.replace(/\.$/g, "");
    },
    isInteger:  function(value) {
         var integerReg =  new RegExp(/^\d+$/);
         return integerReg.test(value);
    },
    isValidateReg:  function(value) {
         var validateReg = /^([A-Za-z0-9\s\-\_\~\!\@\#\$\%\^\&\*\(\)\|\<\>\?\:\;\"\'\.\[\]\{\}\,\+\`\/\\\=]){6,16}$/;
         if (validateReg.test(value)) {
             return  true;
        }
         return  false;
    },
    isDate:  function(strValue) {
         var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/

         if (!objRegExp.test(strValue))
             return  false;
         else {
             var arrayDate = strValue.split(RegExp.$1);
             var intDay = parseInt(arrayDate[2], 10);
             var intYear = parseInt(arrayDate[0], 10);
             var intMonth = parseInt(arrayDate[1], 10);
             if (intMonth > 12 || intMonth < 1) {
                 return  false;
            }
             var arrayLookup = { '1': 31, '3': 31, '4': 30, '5': 31, '6': 30, '7': 31,
                '8': 31, '9': 30, '10': 31, '11': 30, '12': 31
            }
             if (arrayLookup[parseInt(arrayDate[1])] !=  null) {
                 if (intDay <= arrayLookup[parseInt(arrayDate[1])] && intDay != 0)
                     return  true;
            }
             if (intMonth - 2 == 0) {
                 var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
                 if (((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <= 28)) && intDay != 0)
                     return  true;
            }
        }
         return  false;
    },
    isZip:  function(value) {
         var validateReg = /^[0-9]{6}$/;
         return validateReg.test(value);
    },
    checkSpecialChar:  function(value) {
         var validateReg = /([~!@#$%^&*\/\\,.\(\)]){6,16}$/;
         return validateReg.test(value);
    },
    CheckSpecialString:  function(value) {
         var validateReg = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/;
         return validateReg.test(value);
    },
    isTel:  function(s) {
         var patrn = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/
         if (!patrn.exec(s))  return  false
         return  true
    },

    isMobile:  function(value) {
         var validateReg = /^1\d{10}$/;
         return validateReg.test(value);
    },
    getLength:  function(value) {
         return value.replace(/[^\x00-\xff]/g, "**").length;
    },
    isLicence:  function(value) {
         var validateReg = /^[A-Za-z]{10}[0-9]{10}$/;
         return validateReg.test(value);
    },
    isPersonalCard:  function(value) {
         var validateReg = /(^\d{15}$)|(^\d{17}(\d|[A-Za-z]{1})$)/;
         return validateReg.test(value);
    },
    isOrganizationCodeCard:  function(value) {
         var validateReg = /^[A-Za-z0-9]{9}$/;
         return validateReg.test(value);
    },
    isBankAccount:  function(value) {
         var validateReg = /^[1-9]{1}[0-9]*$/;
         return validateReg.test(value);
    },
    MaxLength:  function(field, maxlimit) {
         var j = field.value.replace(/[^\x00-\xff]/g, "**").length;
         var tempString = field.value;
         var tt = "";
         if (j > maxlimit) {
             for ( var i = 0; i < maxlimit; i++) {
                 if (tt.replace(/[^\x00-\xff]/g, "**").length < maxlimit)
                    tt = tempString.substr(0, i + 1);
                 else
                     break;
            }
             if (tt.replace(/[^\x00-\xff]/g, "**").length > maxlimit) {
                tt = tt.substr(0, tt.length - 1);
                field.value = tt;
            }
             else {
                field.value = tt;
            }
        }
    }
};



var ValidateHelper = {
    validateStringValueIsEmpty:  function(obj, normalMsg, warningMsg) {
         var jqueryObj = $(obj);
        ValidateHelper.clearMessage(obj);
         if ($.trim(jqueryObj.val()).length == 0) {
            ValidateHelper.warningMessage(jqueryObj, warningMsg);
             return  false;
        }
         else {
            ValidateHelper.normalMessage(jqueryObj, normalMsg);
             return  true;
        }
    },
    validateStringValueForEmail:  function(obj, normalMsg, warningMsg) {
         var jqueryObj = $(obj);
        ValidateHelper.clearMessage(obj);
         if (!ValidateHelper.validateStringValueIsEmpty(jqueryObj, "通過", "不能為空")) {
            ValidateHelper.warningMessage(jqueryObj, "不能為空");
             return  false;
        }
         if (!Validation.isEmail(jqueryObj.val())) {
            ValidateHelper.warningMessage(jqueryObj, warningMsg);
             return  false;
        }
         else {
            ValidateHelper.normalMessage(jqueryObj, normalMsg);
             return  true;
        }
    },
    validateStringValueForCardID:  function(obj, normalMsg, warningMsg) {
         var jqueryObj = $(obj);
        ValidateHelper.clearMessage(obj);
         if (!ValidateHelper.validateStringValueIsEmpty(jqueryObj, "通過", "不能為空")) {
            ValidateHelper.warningMessage(jqueryObj, "不能為空");
             return  false;
        }
         if (!Validation.isPersonalCard(jqueryObj.val())) {
            ValidateHelper.warningMessage(jqueryObj, warningMsg);
             return  false;
        }
         else {
            ValidateHelper.normalMessage(jqueryObj, normalMsg);
             return  true;
        }
    },
    normalMessage:  function(jqueryObj, msg) {
         var emObj = $(jqueryObj.parent().find('em')[0]);
        emObj.empty().append(msg);
    },
    warningMessage:  function(jqueryObj, msg) {
        ValidateHelper.clearMessage(jqueryObj);
         var emObj = $(jqueryObj.parent().find('em')[0]);
         var spanElement = "<span style='color:#FF4C31;float:left;height:23px;line-height:23px;padding:0 10px 0 35px;'>"
                + msg
                + "</span>";
        emObj.empty().append(spanElement);

    },
    clearMessage:  function(jqueryObj) {
         var emObj = $(jqueryObj.parent().find('em')[0]);
        emObj.empty();
    },
    initInfo:  function() {

         var userName = $('#email');
         var userPwd = $('#setPwd');
         if (!ValidateHelper.validateStringValueIsEmpty(userName, '通過', '不能為空')) {
            userName.focus();
             return  null;
        }
         if (!ValidateHelper.validateStringValueIsEmpty(userPwd, '通過', '不能為空')) {
            userPwd.focus();
             return  null;
        }

         var userInfo = {
            UserName: userName.val(),
            UserPwd: userPwd.val()
        };

         return userInfo;
    },

    post:  function() {

         var userInfo = ValidateHelper.initInfo();
         if (userInfo ==  null) {
             return;
        }

        $.ajax({
            type: "post",
            dataType: "text",
            url: "Ajax/Module.aspx",
            timeout: 30000,
            data: { UserName: userInfo.UserName, UserPwd: userInfo.UserPwd },
            success:  function(data) {
                alert(data.toString());
            }
        });
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM