easyui源码翻译1.32--ValidateBox(验证框)

前言

使用$.fn.validatebox.defaults重写默认值对象。下载该插件翻译源码

validatebox(验证框)的设计目的是为了验证输入的表单字段是否有效。如果用户输入了无效的值,它将会更改输入框的背景颜色,并且显示警告图标和提示信息。该验证框可以结合form(表单)插件并防止表单重复提交。

源码

/**
 * jQuery EasyUI 1.3.2
 * 
 *翻译:qq 1364386878
 */
(function ($) {
    //初始化函数
    function init(jq) {
        $(jq).addClass("validatebox-text");
    };
    //销毁方法
    function _destroy(jq) {
        var validatebox = $.data(jq, "validatebox");
        validatebox.validating = false;
        var tip = validatebox.tip;
        if (tip) {
            tip.remove();
        }
        $(jq).unbind();
        $(jq).remove();
    };
    //绑定事件
    function bindEvents(jq) {
        var box = $(jq);
        var validatebox = $.data(jq, "validatebox");
        //绑定聚焦事件
        box.unbind(".validatebox").bind("focus.validatebox", function () {
            validatebox.validating = true;
            validatebox.value = undefined;
            (function () {
                if (validatebox.validating) {
                    if (validatebox.value != box.val()) {
                        validatebox.value = box.val();
                        if (validatebox.timer) {
                            clearTimeout(validatebox.timer);
                        }
                        validatebox.timer = setTimeout(function () {
                            $(jq).validatebox("validate");
                        }, validatebox.options.delay);
                    } else {
                        validate(jq);
                    }
                    setTimeout(arguments.callee, 200);
                }
            })();
           //绑定光标离开事件
        }).bind("blur.validatebox", function () {
            if (validatebox.timer) {
                clearTimeout(validatebox.timer);
                validatebox.timer = undefined;
            }
            validatebox.validating = false;
            hideTip(jq);
            //绑定鼠标上去
        }).bind("mouseenter.validatebox", function () {
            if (box.hasClass("validatebox-invalid")) {
                showTip(jq);
            }
            //绑定鼠标离开事件
        }).bind("mouseleave.validatebox", function () {
            if (!validatebox.validating) {
                hideTip(jq);
            }
        });
    };
    //显示提示
    function showTip(jq) {
        var message = $.data(jq, "validatebox").message;
        var tip = $.data(jq, "validatebox").tip;
        if (!tip) {
            tip = $("<div class=\"validatebox-tip\">"
                + "<span class=\"validatebox-tip-content\">"
                + "</span>"
                + "<span class=\"validatebox-tip-pointer\">"
                + "</span>" + "</div>").appendTo("body");
            $.data(jq, "validatebox").tip = tip;
        }
        tip.find(".validatebox-tip-content").html(message);
        validate(jq);
    };
    //验证
    function validate(jq) {
        var validatebox = $.data(jq, "validatebox");
        if (!validatebox) {
            return;
        }
        var tip = validatebox.tip;
        if (tip) {
            var box = $(jq);
            var tippointer = tip.find(".validatebox-tip-pointer");
            var tipcontent = tip.find(".validatebox-tip-content");
            tip.show();
            tip.css("top", box.offset().top - (tipcontent._outerHeight() - box._outerHeight()) / 2);
            if (validatebox.options.tipPosition == "left") {
                tip.css("left", box.offset().left - tip._outerWidth());
                tip.addClass("validatebox-tip-left");
            } else {
                tip.css("left", box.offset().left + box._outerWidth());
                tip.removeClass("validatebox-tip-left");
            }
            tippointer.css("top", (tipcontent._outerHeight() - tippointer._outerHeight()) / 2);
        }
    };
    //隐藏提示
    function hideTip(jq) {
        var tip = $.data(jq, "validatebox").tip;
        if (tip) {
            tip.remove();
            $.data(jq, "validatebox").tip = null;
        }
    };
    //验证
    function _validate(jq) {
        var validatebox = $.data(jq, "validatebox");
        var options = validatebox.options;
        var tip = validatebox.tip;
        var box = $(jq);
        var val = box.val();
        function getmsg(msg) {
            validatebox.message = msg;
        };
        //验证类型
        function validTypeMd(validType) {
            var results = /([a-zA-Z_]+)(.*)/.exec(validType);
            var result = options.rules[results[1]];
            if (result && val) {
                var resultsVal = eval(results[2]);
                if (!result["validator"](val, resultsVal)) {
                    box.addClass("validatebox-invalid");
                    var msg = result["message"];
                    if (resultsVal) {
                        for (var i = 0; i < resultsVal.length; i++) {
                            msg = msg.replace(new RegExp("\\{" + i + "\\}", "g"), resultsVal[i]);
                        }
                    }
                    getmsg(options.invalidMessage || msg);
                    if (validatebox.validating) {
                        showTip(jq);
                    }
                    return false;
                }
            }
            return true;
        };
        if (options.required) {
            if (val == "") {
                box.addClass("validatebox-invalid");
                getmsg(options.missingMessage);
                if (validatebox.validating) {
                    showTip(jq);
                }
                return false;
            }
        }
        if (options.validType) {
            if (typeof options.validType == "string") {
                if (!validTypeMd(options.validType)) {
                    return false;
                }
            } else {
                for (var i = 0; i < options.validType.length; i++) {
                    if (!validTypeMd(options.validType[i])) {
                        return false;
                    }
                }
            }
        }
        box.removeClass("validatebox-invalid");
        hideTip(jq);
        return true;
    };
    //实例化验证框
    $.fn.validatebox = function (target, parm) {
        if (typeof target == "string") {
            return $.fn.validatebox.methods[target](this, parm);
        }
        target = target || {};
        return this.each(function () {
            var validatebox = $.data(this, "validatebox");
            if (validatebox) {
                $.extend(validatebox.options, target);
            } else {
                init(this);
                $.data(this, "validatebox", {
                    options: $.extend({},
                        $.fn.validatebox.defaults,
                        $.fn.validatebox.parseOptions(this), target)
                });
            }
            bindEvents(this);
        });
    };
    //默认方法
    $.fn.validatebox.methods = {
        //移除并销毁组件
        destroy: function (jq) {
            return jq.each(function () {
                _destroy(this);
            });
        },
        //验证文本框的内容是否有效
        validate: function (jq) {
            return jq.each(function () {
                _validate(this);
            });
        },
        //调用validate方法并且返回验证结果,true或者false
        isValid: function (jq) {
            return _validate(jq[0]);
        }
    };
    //解析器
    $.fn.validatebox.parseOptions = function (target) {
        var t = $(target);
        return $.extend({}, $.parser.parseOptions(target,
            ["validType",
                "missingMessage",
                "invalidMessage",
                "tipPosition",
                { delay: "number" }]),
                { required: (t.attr("required") ? true : undefined) });
    };
    //默认属性和事件
    $.fn.validatebox.defaults = {
        required: false,//定义为必填字段
        //定义字段验证类型,比如:email, url等等。可用值有:
        //1).一个有效类型字符串运用一个验证规则。
        //2).一个有效类型数组运用多个验证规则
        validType: null,
        delay: 200,//延迟到最后验证输入值
        missingMessage: "This field is required.",//当文本框未填写时出现的提示信息
        invalidMessage: null,//当文本框的内容被验证为无效时出现的提示
        //定义当文本框内容无效的时候提示消息显示的位置,有效的值有:'left','right'
        tipPosition: "right",
        //验证规则
        rules: {
            //匹配E-Mail的正则表达式规则
            email: {
                validator: function (value) {
                    return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
                },
                message: "Please enter a valid email address."
            },
            //匹配URL的正则表达式规则
            url: {
                validator: function (value) {
                    return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
                },
                message: "Please enter a valid URL."
            },
            //length[0,100]:允许在x到x之间个字符
            length: {
                validator: function (startlength, endlength) {
                    var len = $.trim(startlength).length;
                    return len >= endlength[0] && len <= endlength[1];
                },
                message: "Please enter a value between {0} and {1}."
            },
            //remote['http://.../action.do','paramName']:发送ajax请求需要验证的值,当成功时返回true
            remote: {
                validator: function (_2a, url) {
                    var data = {};
                    data[url[1]] = _2a;
                    var _2d = $.ajax({
                        url: url[0],
                        dataType: "json",
                        data: data,
                        async: false,
                        cache: false,
                        type: "post"
                    }).responseText;
                    return _2d == "true";
                },
                message: "Please fix this field."
            }
        }
    };
})(jQuery);
View Code

 

示例代码

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Basic ValidateBox - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="../../themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../../themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../demo.css">
    <script type="text/javascript" src="../../jquery-1.8.0.min.js"></script>
    <script src="../../plugins2/jquery.parser.js"></script>
    <script src="../../plugins2/jquery.validatebox.js"></script>
</head>
<body>
    <h2>Basic ValidateBox</h2>
    <div class="demo-info">
        <div class="demo-tip icon-tip"></div>
        <div>It's easy to add validate logic to a input box.</div>
    </div>
    <div style="margin:10px 0;"></div>
    <div class="easyui-panel" title="Register" style="width:400px;padding:10px">
        <table>
            <tr>
                <td>User Name:</td>
                <td><input class="easyui-validatebox" data-options="required:true,validType:'length[3,10]'"></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input class="easyui-validatebox" data-options="required:true,validType:'email'"></td>
            </tr>
            <tr>
                <td>Birthday:</td>
                <td><input class="easyui-datebox"></td>
            </tr>
            <tr>
                <td>URL:</td>
                <td><input class="easyui-validatebox" data-options="required:true,validType:'url'"></td>
            </tr>
            <tr>
                <td>Phone:</td>
                <td><input class="easyui-validatebox" data-options="required:true"></td>
            </tr>
        </table>
    </div>

</body>
</html>
View Code

 

插件效果

posted @ 2014-01-01 23:12  Jimmy-Lee  阅读(1547)  评论(0编辑  收藏  举报