SoFunction
Updated on 2025-03-01

Specific methods for self-implementation of js verification model

There are many form verification frameworks on the market, which teach us how to verify the data submission of forms. To be honest, it is really simple, but we have a feeling that if we leave these frameworks, we will sometimes be helpless, and then the js verification is written very irregularly and there is no better model. Then the purpose of my writing this article is: we should build what js verification should look like by ourselves, let’s take a look.
Suppose we now write a login page (this may be the simplest data submission), and the html page will have a text box with a username and password for us to enter our username and password. We must determine whether the username and password are empty. It is obvious that such js verification judgment is triggered in the onblur event. The html code is as follows:

ValidateHelper is an object, and some verification methods are included in this object. Let us specify that there are two results for the input of the js verification user, one is successful and the other is failure. When successful, we output a prompt for success.
When we fail, we output the prompt of failure, and the corresponding two output methods:

Copy the codeThe code is as follows:

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

    },


There is also a way to clear the prompt:
Copy the codeThe code is as follows:

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

We have written the success and failure prompt methods, as well as the method to clear the prompt. These three are the basic methods we will keep calling later.
OK, let's write a method to verify that user input cannot be empty:
Copy the codeThe code is as follows:

    validateStringValueIsEmpty: function(obj, normalMsg, warningMsg) {
        var jqueryObj = $(obj);
        (obj);
        if ($.trim(()).length == 0) {
            (jqueryObj, warningMsg);
            return false;
        }
        else {
            (jqueryObj, normalMsg);
            return true;
        }
    },

This method will be called in the verification method in the onblur, and naturally uses the success and failure prompt methods, as well as the clear prompt methods. There are three parameters: Dom or jQuery object to be verified, success prompt information, and failure prompt message
interest. If it is empty, it will fail, and if it is not empty, it will succeed.
The above method will be triggered in onblur, and we will also use it when submitting data:
Copy the codeThe code is as follows:

    initInfo: function() {

        var userName = $('#email');
        var userPwd = $('#setPwd');
if (!(userName, 'pass', 'can't be empty')) {
            ();
            return null;
        }
if (!(userPwd, 'pass', 'can't be empty')) {
            ();
            return null;
        }

        var userInfo = {
            UserName: (),
            UserPwd: ()
        };

        return userInfo;
    },

    post: function() {

        var userInfo = ();
        if (userInfo == null) {
            return;
        }

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


If the validateStringValueIsEmpty method is called when submitting data, if the returned failure, it will not be submitted to the server.
The above situation is the simplest case where it is not empty. If we want to verify whether it is an email or an ID number, these complex verification implementations are as follows:
Copy the codeThe code is as follows:

var Validation = {
    textCount: function(field, counter, maxLimit) {
        var message = $(field).val();
        if ($(field).val().length > maxLimit)
            $(field).val((0, maxLimit))
        //$(counter).text();   
    },
    refreshValidator: function(img, input) {
        $(img).attr('src', $(img).attr('src') + "&r=" + ());
        $(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 (s);
    },
    isDecimal: function(d) { var pattern = /^(([1-9]\d{0,12})|0)(\.\d{1,2})?$/; return (d); },
    isEmail: function(s) {
        var pattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
        return (s);
    },
    isLowEmail: function(s) {
        var b, e;
        b = ("@");
        e = (".");
        if (b <= 0) return false;
        if (e < 0 || e == ( - 1)) { return false; }
        return true;
    },
    clearNoNum: function(event, obj) {
        event = || event;
        if ( == 37 | == 39) {
            return;
        }
        = (/[^\d.]/g, "");
        = (/^\./g, "");
        = (/\.{2,}/g, ".");
        = (".", "$#$").replace(/\./g, "").replace("$#$", ".");
    },
    checkNum: function(obj) {
        = (/\.$/g, "");
    },
    isInteger: function(value) {
        var integerReg = new RegExp(/^\d+$/);
        return (value);
    },
    isValidateReg: function(value) {
        var validateReg = /^([A-Za-z0-9\s\-\_\~\!\@\#\$\%\^\&\*\(\)\|\<\>\?\:\;\"\'\.\[\]\{\}\,\+\`\/\\\=]){6,16}$/;
        if ((value)) {
            return true;
        }
        return false;
    },
    isDate: function(strValue) {
        var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/

        if (!(strValue))
            return false;
        else {
            var arrayDate = (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 (value);
    },
    checkSpecialChar: function(value) {
        var validateReg = /([~!@#$%^&*\/\\,.\(\)]){6,16}$/;
        return (value);
    },
    CheckSpecialString: function(value) {
        var validateReg = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/;
        return (value);
    },
    isTel: function(s) {
        var patrn = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/
        if (!(s)) return false
        return true
    },

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



This class writes some regular expressions that verify email, ID number, etc. for us to use later. The usage method is as follows:
Copy the codeThe code is as follows:

    validateStringValueForEmail: function(obj, normalMsg, warningMsg) {
        var jqueryObj = $(obj);
        (obj);
if (!(jqueryObj, "pass", "can't be empty")) {
(jqueryObj, "can't be empty");
            return false;
        }
        if (!(())) {
            (jqueryObj, warningMsg);
            return false;
        }
        else {
            (jqueryObj, normalMsg);
            return true;
        }
    },
    validateStringValueForCardID: function(obj, normalMsg, warningMsg) {
        var jqueryObj = $(obj);
        (obj);
if (!(jqueryObj, "pass", "can't be empty")) {
(jqueryObj, "can't be empty");
            return false;
        }
        if (!(())) {
            (jqueryObj, warningMsg);
            return false;
        }
        else {
            (jqueryObj, normalMsg);
            return true;
        }
    },


Then here we can basically handle our general JS verification. You can try to use it on your own framework in the future. We attach the source code we debugged:
ASPX :
Copy the codeThe code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="" Inherits="FormValidateModuleEx._Default" %>

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

    <script src="js\jquery-1.6." type="text/javascript"></script>
    <script src="js\" type="text/javascript"></script>
    <%--<script src="js\" type="text/javascript"></script>--%>
</head>
<body>
    <div>
        <li>
            <label for="email">
username:
            </label>
<input name="email" type="text" maxlength="50" onblur="return ($(this),'pass','can't be empty');" /><em></em>
        </li>
        <li>
            <label for="setPwd">
password:
            </label>
<input name="setPwd" type="password" maxlength="16" onblur="return ($(this),'pass','can't be empty');" /><em></em>
        </li>
        <li>
            <label for="setPwd">
ID card:
            </label>
<input name="cardId" type="text" onblur="return ($(this),'pass','Identity card format is incorrect');" /><em></em><%--IdCardValidate($(this),'Identity card format is incorrect');-%>
        </li>
        <li>
            <label for="setPwd">
                Email:
            </label>
<input name="againEmail" type="text" onblur="return ($(this),'pass','email format is incorrect');" /><em></em>
        </li>
        <li><input onclick="return ();" type="button" /></li>
    </div>
</body>
</html>


js:
Copy the codeThe code is as follows:

var Validation = {
    textCount: function(field, counter, maxLimit) {
        var message = $(field).val();
        if ($(field).val().length > maxLimit)
            $(field).val((0, maxLimit))
        //$(counter).text();   
    },
    refreshValidator: function(img, input) {
        $(img).attr('src', $(img).attr('src') + "&r=" + ());
        $(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 (s);
    },
    isDecimal: function(d) { var pattern = /^(([1-9]\d{0,12})|0)(\.\d{1,2})?$/; return (d); },
    isEmail: function(s) {
        var pattern = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
        return (s);
    },
    isLowEmail: function(s) {
        var b, e;
        b = ("@");
        e = (".");
        if (b <= 0) return false;
        if (e < 0 || e == ( - 1)) { return false; }
        return true;
    },
    clearNoNum: function(event, obj) {
        event = || event;
        if ( == 37 | == 39) {
            return;
        }
        = (/[^\d.]/g, "");
        = (/^\./g, "");
        = (/\.{2,}/g, ".");
        = (".", "$#$").replace(/\./g, "").replace("$#$", ".");
    },
    checkNum: function(obj) {
        = (/\.$/g, "");
    },
    isInteger: function(value) {
        var integerReg = new RegExp(/^\d+$/);
        return (value);
    },
    isValidateReg: function(value) {
        var validateReg = /^([A-Za-z0-9\s\-\_\~\!\@\#\$\%\^\&\*\(\)\|\<\>\?\:\;\"\'\.\[\]\{\}\,\+\`\/\\\=]){6,16}$/;
        if ((value)) {
            return true;
        }
        return false;
    },
    isDate: function(strValue) {
        var objRegExp = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/

        if (!(strValue))
            return false;
        else {
            var arrayDate = (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 (value);
    },
    checkSpecialChar: function(value) {
        var validateReg = /([~!@#$%^&*\/\\,.\(\)]){6,16}$/;
        return (value);
    },
    CheckSpecialString: function(value) {
        var validateReg = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/;
        return (value);
    },
    isTel: function(s) {
        var patrn = /^\d{3,4}-\d{7,8}(-\d{3,4})?$/
        if (!(s)) return false
        return true
    },

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


var ValidateHelper = {
    validateStringValueIsEmpty: function(obj, normalMsg, warningMsg) {
        var jqueryObj = $(obj);
        (obj);
        if ($.trim(()).length == 0) {
            (jqueryObj, warningMsg);
            return false;
        }
        else {
            (jqueryObj, normalMsg);
            return true;
        }
    },
    validateStringValueForEmail: function(obj, normalMsg, warningMsg) {
        var jqueryObj = $(obj);
        (obj);
if (!(jqueryObj, "pass", "can't be empty")) {
(jqueryObj, "can't be empty");
            return false;
        }
        if (!(())) {
            (jqueryObj, warningMsg);
            return false;
        }
        else {
            (jqueryObj, normalMsg);
            return true;
        }
    },
    validateStringValueForCardID: function(obj, normalMsg, warningMsg) {
        var jqueryObj = $(obj);
        (obj);
if (!(jqueryObj, "pass", "can't be empty")) {
(jqueryObj, "can't be empty");
            return false;
        }
        if (!(())) {
            (jqueryObj, warningMsg);
            return false;
        }
        else {
            (jqueryObj, normalMsg);
            return true;
        }
    },
    normalMessage: function(jqueryObj, msg) {
        var emObj = $(().find('em')[0]);
        ().append(msg);
    },
    warningMessage: function(jqueryObj, msg) {
        (jqueryObj);
        var emObj = $(().find('em')[0]);
        var spanElement = "<span style='color:#FF4C31;float:left;height:23px;line-height:23px;padding:0 10px 0 35px;'>"
                + msg
                + "</span>";
        ().append(spanElement);

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

        var userName = $('#email');
        var userPwd = $('#setPwd');
if (!(userName, 'pass', 'can't be empty')) {
            ();
            return null;
        }
if (!(userPwd, 'pass', 'can't be empty')) {
            ();
            return null;
        }

        var userInfo = {
            UserName: (),
            UserPwd: ()
        };

        return userInfo;
    },

    post: function() {

        var userInfo = ();
        if (userInfo == null) {
            return;
        }

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