首頁 > web前端 > js教程 > js验证模型自我实现的具体方法_javascript技巧

js验证模型自我实现的具体方法_javascript技巧

WBOY
發布: 2016-05-16 17:31:59
原創
1105 人瀏覽過

市面上有很多表单验证的框架,教我们怎么验证表单的数据提交,说实话也真的很简单,但是我们会有一种感觉我们要是离开了这些框架的时候,我们有时候会束手无策,然后js验证写的很不规范,没有一套比较好的模式,那我写这篇的目的就是:我们自己构建js验证应该是什么样子的,来慢慢看一下。
假设我们现在写一个登录的页面(这可能是最简单的数据提交了哦),html页面会有一个用户名和一个密码的文本框让我们用户输入自己的用户名和密码,我们肯定是要判断用户名和密码是否为空,很明显这样的js验证判断是放在onblur事件里面触发,html代码如下:

ValidateHelper是一个对象,一些验证的方法就是在这个对象里面,我们规定一下,js验证用户的输入有两返回结果,一个成功,一个是失败。成功的时候我们输出成功的提示,
失败的时候我们输出失败的提示,对应的两个输出方法:

复制代码 代码如下:

    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 = ""
                + msg
                + "
";
        emObj.empty().append(spanElement);

    },


还有一个清除提示的方法:
复制代码 代码如下:

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

我们已经写了成功和失败提示方法,以及清除提示的方法,这个三个是我们在后面会一直调用的基本方法。
好了,我们写一个验证用户输入不能为空的方法:
复制代码 代码如下:

    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中会触发的,我们提交数据的时候还会用到得哦:
复制代码 代码如下:

    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         if (e         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                 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                     return true;
            }
            if (intMonth - 2 == 0) {
                var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
                if (((booLeapYear && intDay                     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                 if (tt.replace(/[^\x00-\xff]/g, "**").length                     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 :
复制代码 代码如下:




   

   
   
    --%>


   

       

  •            
               
           

  •        

  •            
               
           

  •        

  •            
               
           

  •        

  •            
               
           

  •        

  •    




    js:
    复制代码 代码如下:

    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         if (e         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                 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                     return true;
                }
                if (intMonth - 2 == 0) {
                    var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
                    if (((booLeapYear && intDay                     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                 if (tt.replace(/[^\x00-\xff]/g, "**").length                     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 = ""
                    + msg
                    + "
    ";
            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());
                }
            });
        }
    }

    相關標籤:
    來源:php.cn
    本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
    最新問題
    熱門教學
    更多>
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板