用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - javascript代码库

原生js代码表单验证插件 提供常用的10种表单验证方式

2018-10-24 作者:longgeme举报

[javascript]代码库

verjs是一款原生js代码编写的表单验证插件,提供了常用的10种表单验证方式,包括身份证号码验证、手机电话号码、电子邮箱验证、必填字段验证、正则自定义验证、多次对比验证、最大值/最小值验证……

html代码:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
    <meta content="yes" name="apple-mobile-web-app-capable"/>
    <meta content="black" name="apple-mobile-web-app-status-bar-style"/>
    <meta content="telephone=no" name="format-detection"/>
    <meta content="email=no" name="format-detection"/>
    <meta content="initial-scale=1.0,user-scalable=no,maximum-scale=1" media="(device-height: 568px)" name="viewport"/>
    <title>verJs</title>
    <style>
        dl dt,dl dd{
            display: inline-block;
        }

        input{
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
        }

        textarea{
            resize: none;
            width: 120px;
            line-height: 30px;
            padding: 0 10px;
            height: 120px;
        }
    </style>
</head>
<body>
<form action="http://www.sucaihuo.com/js/3969.html" method="post" autocomplete="off" data-form="ajax">
    <dl>
        <dt>必填验证</dt>
        <dd>
            <input type="text" name="req">
        </dd>
    </dl>
    <dl>
        <dt>最小数字</dt>
        <dd>
            <input type="text" name="min_number">
        </dd>
    </dl>
    <dl>
        <dt>最大数字</dt>
        <dd>
            <input type="text" name="max_number" id="eq">
        </dd>
    </dl>
    <dl>
        <dt>相等比较</dt>
        <dd>
            <input type="text" name="eq">
        </dd>
    </dl>
    <dl>
        <dt>最小长度</dt>
        <dd>
            <input type="text" name="min_length">
        </dd>
    </dl>
    <dl>
        <dt>最大长度</dt>
        <dd>
            <input type="text" name="max_length">
        </dd>
    </dl>
    <dl>
        <dt>正则验证</dt>
        <dd>
            <input type="password" name="rule">
        </dd>
    </dl>
    <dl>
        <dt>手机/电话验证</dt>
        <dd>
            <input type="text" name="mobile">
        </dd>
    </dl>
    <dl>
        <dt>邮箱验证</dt>
        <dd>
            <input type="text" name="email" data-email="true">
        </dd>
    </dl>
    <dl>
        <dt>身份证验证</dt>
        <dd>
            <input type="text" name="email" data-idcard="true">
        </dd>
    </dl>
    <button>提交代码</button>
</form>
</body>
<script src="asset/verJs.js"></script>
<script>
    var form = new VerJs();
    form.init({
        form:"form",//验证的表单
        //验证数据集,也可以在标记中以data-XXX的形式加入验证
        data:{
            req:{
                required:true
            },
            min_number:{
                min:2
            },
            max_number:{
                max:12
            },
            eq:{
                equal:"#eq"
            },
            min_length:{
                minlength:6
            },
            max_length:{
                maxlength:6
            },
            rule:{
                rule:"^\\d{6}$",
                required:true
            },
            mobile:{
                mobile:true
            }
        },
        //验证提示消息
        message:{
            req:{
                required:"这是一条必填数据"
            },
            rule:{
                rule:"请输入六位数字"
            }
        },
        success:function (data) {
            //ajax提交成功后的回调函数
            alert("hahahha");
        },
        fail:function (data) {
            //ajax提交失败后的回调函数
            alert("ieieiiruwei");
        }
    });
</script>
</html>

VerJs.js里面的代码:
window.VerJs = (function () {
    var ver = function () {
        this.form;
        this.messages = {
            required: "当前选项不能为空!",
            min: 0,
            max: 0,
            minlength: 0,
            maxlength: 0,
            rule: "",
            equal: "",
            mobile: "请输入有效的手机号码",
            email: "请输入规则的电子邮箱",
            idcard: "请输入有效的身份证号码"
        };
        this.func = {
            required: this.data_required,
            min: this.data_min_value,
            max: this.data_max_value,
            minlength: this.data_min_length,
            maxlength: this.data_max_length,
            rule: this.data_rule,
            equal: this.data_equal,
            mobile: this.data_mobile,
            email: this.data_email,
            idcard: this.data_id_card
        };
        this.change;
        this.error = function (errorMessage, target) {
            this.clear_error(target);
            target.classList.add("ver-error-input");
            var errorTag = document.createElement("span");
            errorTag.className = "ver-errors";
            var iconCarets = document.createElement("i");
            iconCarets.className = "verJsFont ver-icon-carets ver-error-caret";
            errorTag.appendChild(iconCarets);
            var iconInfo = document.createElement("i");
            iconInfo.className = "verJsFont icon-info-o";
            errorTag.appendChild(iconInfo);
            var span = document.createElement("span");
            span.innerText = errorMessage;
            errorTag.appendChild(span);
            this.insertAfter(errorTag, target);
        };
        this.insertAfter = function (newElement, targentElement) {
            var parent = targentElement.parentNode;
            if (parent.lastChild == targentElement) {
                parent.appendChild(newElement);
            } else {
                parent.insertBefore(newElement, targentElement.nextSibling);
            }
        };
        this.styles = function () {
            var css = document.createElement("link"),
                icon = document.createElement("link");
            css.href = "asset/need/common.css?v=1.0.2&$_=" + Math.random();
            icon.href = "asset/need/vericon.css?v=1.0.2&$_=" + Math.random();
            css.rel = icon.rel = "stylesheet";
            css.type = icon.type = "text/css";
            var link = document.getElementsByTagName("head")[0];
            link.appendChild(css);
            link.appendChild(icon);
        };
        this.success = function (data) {
            alert("提交成功!")
        }
        this.fail = function (data) {
            alert("提交失败!");
        }
    };
    ver.prototype = {
        init: function (params) {
            var _self = this;
            this.styles();
            this.form = document.querySelector(params.form);
            if (!this.form) this.form = document.querySelector("form");
            this.change = params.change ? params.change : "default";
            this._sef_data(params.data, params.message);
            this.form.onsubmit = function () {
                return _self.submit();
            };
            if (params.success) {
                this.success = params.success;
            }
            if (params.fail) {
                this.fail = params.fail;
            }
        },
        submit: function () {
            this.verification();
            var error = this.form.querySelectorAll(".ver-error-input").length;
            if (error > 0) {
                this.form.querySelector(".ver-error-input").focus();
                return false;
            }
            var form = this.form.getAttribute("data-form");
            if (form == "ajax") {
                this.ajax();
                return false;
            }
            return true;
        },
        _sef_data: function (data, message) {
            var _self = this;
            if (data) {
                for (var i in data) {
                    var names = document.getElementsByName(i);
                    names.forEach(function (item) {
                        for (var j in data[i]) {
                            var messages = message && message[i] && message[i][j] ? message[i][j] : _self.messages[j];
                            if (j != "min" && j != "max" && j != "minlength" && j != "maxlength" && j != "rule" && j != "equal") {
                                item.setAttribute("data-" + j, messages);
                            } else if (j == "rule") {
                                item.setAttribute("data-rule", data[i][j]);
                                item.setAttribute("data-rule-message", messages);
                            } else {
                                item.setAttribute("data-" + j, data[i][j]);
                            }

                        }
                    })
                }
            }

            //判断标记中是否有data验证的数据标记
            for (var i in this.messages) {
                var names = this.form.querySelectorAll("[data-" + i + "]");
                names.forEach(function (items) {
                    var val = items.getAttribute("data-" + i);
                    if (val == "true" || val == "false") {
                        items.setAttribute("data-" + i, _self.messages[i]);
                    }
                    items.onblur = function () {
                        _self.query(this);
                    };
                    items.change = function () {
                        _self.query(this);
                    };
                    items.onfocus = function () {
                        _self.clear_error(this);
                    };
                    if (_self.change == "keyup") {
                        items.onkeyup = function () {
                            _self.query(this);
                        }
                    }
                })
            }
        },
        verification: function () {
            var _self = this;
            for (var i in this.func) {
                var names = this.form.querySelectorAll("[data-" + i + "]");
                if (names.length > 0) {
                    names.forEach(function (items) {
                        _self.func[i](items, _self);
                    })
                }
            }
        },
        query: function (objects) {
            for (var i in this.func) {
                if (objects.getAttribute("data-" + i)) {
                    this.func[i](objects, this);
                }
            }
        },
        clear_error: function (objects) {
            var parent = objects.parentNode,
                errorTag = parent.querySelector(".ver-errors");
            if (errorTag) {
                parent.removeChild(errorTag);
            }
            objects.classList.remove("ver-error-input");
        },
        data_required: function (objects, _self) {
            var value = objects.value,
                errorMessage = objects.getAttribute("data-required");
            if (value == '' || value == null) {
                _self.error(errorMessage, objects);
                return false;
            }
            return true;
        },
        data_min_value: function (objects, _self) {
            var value = (objects.value),
                min = parseInt(objects.getAttribute("data-min"));
            if (value) {
                value == parseInt(value);
                if (isNaN(value) || min > value) {
                    _self.error("最小值为:" + min, objects);
                    return false;
                }
            }
            return true;
        },
        data_max_value: function (objects, _self) {
            var value = (objects.value),
                min = parseInt(objects.getAttribute("data-max"));
            if (value) {
                value = parseInt(value);
                if (isNaN(value) || min < value) {
                    _self.error("最大值为:" + min, objects);
                    return false;
                }
            }
            return true;
        },
        data_min_length: function (objects, _self) {
            var value = objects.value.length,
                min = parseInt(objects.getAttribute("data-minlength"));
            if (value < min) {
                _self.error("最少输入" + min + "个字符", objects);
                return false;
            }
            return true;
        },
        data_max_length: function (objects, _self) {
            var value = objects.value.length,
                min = parseInt(objects.getAttribute("data-maxlength"));
            if (value > min) {
                _self.error("最多输入" + min + "个字符", objects);
                return false;
            }
            return true;
        },
        data_rule: function (objects, _self) {
            var value = objects.value,
                rule = objects.getAttribute("data-rule"),
                errorMessage = objects.getAttribute("data-rule-message");
            if (!errorMessage) errorMessage = "格式错误!";
            rule = new RegExp(rule);
            if (value) {
                if (!rule.test(value)) {
                    _self.error(errorMessage, objects);
                    return false;
                }
            }
            return true;
        },
        data_equal: function (objects, _self) {
            var value = objects.value,
                equal = document.querySelector(objects.getAttribute("data-equal")).value,
                errorMessage = "两次输入内容不一致";
            if (value != equal) {
                _self.error(errorMessage, objects);
                return false;
            }
            return true;
        },
        data_mobile: function (object, _self) {
            var value = object.value,
                rule_tel = /^(0\d{2,3}\d{7,8}|0\d{2,3}-)\d{7,8}$/,
                rule_phone = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
                errorMessage = object.getAttribute("data-mobile");
            if (value && !rule_phone.test(value) && !rule_tel.test(value)) {
                _self.error(errorMessage, object);
                return false;
            }
            return true;
        },
        data_email: function (object, _self) {
            var value = object.value,
                rule_email = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g,
                errorMessage = object.getAttribute("data-email");
            if (value && !rule_email.test(value)) {
                _self.error(errorMessage, object);
                return false;
            }
            return true;
        },
        data_id_card: function (object, _self) {
            var value = object.value,
                rule_email = /^([1-9]\d{5}[1]\d{3}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[0-9xX]|[1-9]\d{5}\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3})$/,
                errorMessage = object.getAttribute("data-idcard");
            if (value && !rule_email.test(value)) {
                _self.error(errorMessage, object);
                return false;
            }
            return true;
        },
        ajax: function () {
            var _self = this;
            var data = this.formData();
            var xhr = new XMLHttpRequest();
            xhr.open(this.form.method, this.form.action, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200 || xhr.status == 304) {
                        _self.success(xhr.responseText);
                    } else {
                        _self.fail(xhr.responseText);
                    }
                }
            };
            xhr.send(data);
        },
        formData: function () {
            var ele = [],
                inputs = this.form.querySelectorAll("input"),
                select = this.form.querySelectorAll("select"),
                text = this.form.querySelectorAll("textarea");
            if (inputs.length > 0) {
                inputs.forEach(function (items) {
                    // ele.push(items);
                    var type = items.type.toLowerCase(),
                        value = "";
                    if (type !== 'checkbox' && type != "radio") {
                        value = items.name + "=" + items.value;
                    } else {
                        if (items.checked) {
                            value = items.name + "=" + items.value;
                        }
                    }
                    if (value) {
                        ele.push(value);
                    }
                });
            }

            if (select.length > 0) {
                select.forEach(function (items) {
                    ele.push(items.name + "=" + items.value);
                })
            }

            if (text.length > 0) {
                text.forEach(function (items) {
                    ele.push(items.name + "=" + items.value);
                })
            }
            return encodeURI(ele.join("&"));
        }
    };
    return ver;
})();

[代码运行效果截图]


原生js代码表单验证插件 提供常用的10种表单验证方式


分享到:
更多

网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。