当前位置: 代码迷 >> JavaScript >> JS印证控件1.3
  详细解决方案

JS印证控件1.3

热度:184   发布时间:2013-09-26 10:32:35.0
JS验证控件1.3

更新内容:

1.新增可以自定义提示参数名

2.提交等事件可以只绑定一次

3.整合一些常用的验证到里面去


var urlHelp = {};
// 跳转页面
urlHelp.GoUrl = function(url, addbackurl) {
    if (addbackurl != true)
        addbackurl = false;

    if (addbackurl == true) {
        var backurl = urlHelp.request('backurl');
        if (backurl != null && backurl != undefined && backurl != "") {
            url = urlHelp.setRequest(url, "backurl", backurl);
        }
    }
    location.replace(url);
}
//得到当前页面URL
urlHelp.getPageUrl = function() {
    var oldurl = location.href;

    var url = oldurl.substring(oldurl.length - 1, oldurl.length);
    while (url == "#") {
        oldurl = oldurl.substring(0, oldurl.length - 1);
        url = oldurl.substring(oldurl.length - 1, oldurl.length);
    }
    oldurl = urlHelp.setRequest(oldurl, "mathrandom", Math.random());
    return oldurl;


    if (oldurl.indexOf('?') != -1) {
        var index = oldurl.lastIndexOf("&", oldurl.length);
        if (index != -1) {
            var a = oldurl.substring(index + 1, oldurl.length);
            if (!isNaN(a)) {
                oldurl = oldurl.substring(0, index)
            }
        }
        oldurl = oldurl + "&" + Math.random();
    }
    else {
        oldurl = oldurl + "?" + Math.random();
    }
    return oldurl;
}
//对内容进行编码
urlHelp.getEncodeURI = function(content) {
    content = encodeURIComponent(content);
    content = urlHelp.MyReplace(content, "#", "%23");
    return content;
}
// 对内容进行替换
urlHelp.MyReplace = function(content, value1, value2) {
    var reg = new RegExp(value1, "g");
    content = content.replace(reg, value2);
    return content;
}
// 获取URL参数
urlHelp.request = function(paras) {
    var url = location.href;
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {}
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof (returnValue) == "undefined") {
        return "";
    } else {
        return urlHelp.MyReplace(returnValue, '#', '');
    }
}

urlHelp.setRequest = function(url, par, par_value) {
    var pattern = par + '=([^&]*)';
    var replaceText = par + '=' + par_value;

    if (url.match(pattern)) {
        var tmp = '/\\' + par + '=[^&]*/';
        tmp = url.replace(eval(tmp), replaceText);
        return (tmp);
    }
    else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        }
        else {
            return url + '?' + replaceText;
        }
    }

    return url;
}
// JavaScript Document
if (typeof (HTMLElement) != "undefined") {
    HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode) {
        switch (where) {
            case "beforeBegin":
                this.parentNode.insertBefore(parsedNode, this);
                break;
            case "afterBegin":
                this.insertBefore(parsedNode, this.firstChild);
                break;
            case "beforeEnd":
                this.appendChild(parsedNode);
                break;
            case "afterEnd":
                if (this.nextSibling)
                    this.parentNode.insertBefore(parsedNode, this.nextSibling);
                else
                    this.parentNode.appendChild(parsedNode);
                break;
        }
    }
    HTMLElement.prototype.insertAdjacentHTML = function(where, htmlStr) {
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var parsedHTML = r.createContextualFragment(htmlStr);
        this.insertAdjacentElement(where, parsedHTML);
    }
    HTMLElement.prototype.insertAdjacentText = function(where, txtStr) {
        var parsedText = document.createTextNode(txtStr);
        this.insertAdjacentElement(where, parsedText);
    }
}


function addEvent(element, type, handler, funname) {
    if (!element) {
        return;
    }
    //为每一个事件处理函数分派一个唯一的ID
    if (!handler.$$guid) handler.$$guid = addEvent.guid++;
    try {
        if (!funname) funname = handler.$$guid;
        if (!element.funnames) element.setAttribute('funnames', "");
        if (element.funnames.split(',').Any(funname)) {
            return;
        }
    } catch (e) { }


    //为元素的事件类型创建一个哈希表
    if (!element.events) element.events = {};
    //为每一个"元素/事件"对创建一个事件处理程序的哈希表
    var handlers = element.events[type];
    if (!handlers) {
        handlers = element.events[type] = {};
        //存储存在的事件处理函数(如果有)
        if (element["on" + type]) {
            handlers[0] = element["on" + type];
        }
    }
    //将事件处理函数存入哈希表
    handlers[handler.$$guid] = handler;
    //指派一个全局的事件处理函数来做所有的工作
    element["on" + type] = handleEvent;
    try {
        element.setAttribute('funnames', element.funnames + funname + ",");
    } catch (e) { }
};
//用来创建唯一的ID的计数器
addEvent.guid = 1;
function removeAllEvent(element, type) {
    if (element && element.events && element.events != null) {
        element.events[type] = {};
    }
}
function removeEvent(element, type, handler) {
    //从哈希表中删除事件处理函数 www.2cto.com
    if (element && element.events && element.events[type]) {
        delete element.events[type][handler.$$guid];
    }
};
function handleEvent(event) {
    var returnValue = true;
    try {
        //抓获事件对象(IE使用全局事件对象)
        event = event || fixEvent(window.event);
        //取得事件处理函数的哈希表的引用
        var handlers = this.events[event.type];
        //执行每一个处理函数
        for (var i in handlers) {
            this.$$handleEvent = handlers[i];
            if (this.$$handleEvent(event) === false) {
                returnValue = false;
            }
        }
    } catch (e) { }
    return returnValue;
};
//为IE的事件对象添加一些“缺失的”函数
function fixEvent(event) {
    if (event != null) {


        //添加标准的W3C方法
        event.preventDefault = fixEvent.preventDefault;
        event.stopPropagation = fixEvent.stopPropagation;
    }
    return event;
};
fixEvent.preventDefault = function() {
    this.returnValue = false;
};
fixEvent.stopPropagation = function() {
    this.cancelBubble = true;
};
Array.prototype.S = String.fromCharCode(2);

Array.prototype.Any = function(e) {

    var r = new RegExp(this.S + e + this.S);

    return (r.test(this.S + this.join(this.S) + this.S));

};

function addEvent(element, type, handler, funname) {
    //为每一个事件处理函数分派一个唯一的ID
    if (!handler.$$guid) handler.$$guid = addEvent.guid++;
    try {
        if (!funname) funname = handler.$$guid;
        var funnames = element.getAttribute("funnames");
        if (funnames == null || funnames == "") { element.setAttribute("funnames", ""); funnames = ""; }
        if (funnames.split(',').Any(funname)) {
            return;
        }
    } catch (e) { }

    //为元素的事件类型创建一个哈希表
    if (!element.events) element.events = {};
    //为每一个"元素/事件"对创建一个事件处理程序的哈希表
    var handlers = element.events[type];
    if (!handlers) {
        handlers = element.events[type] = {};
        //存储存在的事件处理函数(如果有)
        if (element["on" + type]) {
            handlers[0] = element["on" + type];
        }
    }
    //将事件处理函数存入哈希表
    handlers[handler.$$guid] = handler;
    //指派一个全局的事件处理函数来做所有的工作
    element["on" + type] = handleEvent;
    try {
        element.setAttribute('funnames', element.getAttribute("funnames") + funname + ",");
    } catch (e) { }
};
//用来创建唯一的ID的计数器
addEvent.guid = 1;
function removeAllEvent(element, type) {

    if (element.events && element.events != null) {
        try {
            element.events[type] = {};
            element.setAttribute("funnames", "");
        } catch (e) {}

    }
}
function removeEvent(element, type, handler) {
    //从哈希表中删除事件处理函数 www.2cto.com
    if (element.events && element.events[type]) {
        delete element.events[type][handler.$$guid];
    }
};
function handleEvent(event) {
    var returnValue = true;
    try {
        //抓获事件对象(IE使用全局事件对象)
        event = event || fixEvent(window.event);
        //取得事件处理函数的哈希表的引用
        var handlers = this.events[event.type];
        //执行每一个处理函数
        for (var i in handlers) {
            this.$$handleEvent = handlers[i];
            if (this.$$handleEvent(event) === false) {
                returnValue = false;
            }
        }
    } catch (e) { }
    return returnValue;
};
//为IE的事件对象添加一些“缺失的”函数
function fixEvent(event) {
    if (event != null) {

        //添加标准的W3C方法
        event.preventDefault = fixEvent.preventDefault;
        event.stopPropagation = fixEvent.stopPropagation;
    }
    return event;
};
fixEvent.preventDefault = function() {
    this.returnValue = false;
};
fixEvent.stopPropagation = function() {
    this.cancelBubble = true;
};



function dataValidator() {
    var self = this;
    this.model = "";
    this.field = "";
    this.value = "";
    this.id = "";
    this.msgid = ""; //显示错误ID
    this.btnid = ""; //按钮ID
    this.successMsg = ""
    this.callback = function(xmlhttp) {
        if (xmlhttp.readyState == 0 || xmlhttp.status == 0) {
            return;
        }
        var msg = document.getElementById(self.msgid);
        var btn = document.getElementById(self.btnid);

        var ss = xmlhttp.responseText.split('||');
        var code = ss[0];
        var message = "";
        if (ss[1]) {
            message = ss[1];
        }
        if (code == "0") {
            msg.innerHTML = message;
            msg.style.color = 'red';
            btn.disabled = true;
        }
        else {
            msg.innerHTML = self.successMsg;
            msg.style.color = 'green';
            btn.disabled = false;
        }
    }
    this.send = function() {
        $.ajax({
            type: "POST",
            url: "DataValidator.ashx",
            data: "action=validator&model=" + this.model + "&field=" + this.field + "&value=" + this.value + "&id=" + this.id,
            complete: function(response, a, b) {
                self.callback(response);
                return;

            }
        });
    }
}
function ValidatorAlert(message) {
    try {
        var easyui = typeof (jQuery) == 'undefined' ? null : jQuery;
        if (!easyui || easyui.messager == null || easyui.messager == undefined || !easyui.messager) { easyui = typeof (window.parent.jQuery) == 'undefined' ? null : window.parent.jQuery; }
        if (easyui) {
            easyui.messager.alert('操作提示', message);
        } else {
            alert(message);
        }
    } catch (e) {
        alert(message);
    }
}



//验证控件
var Validator = function(formid, event) {
    Upload.fileChage();
    var $$ = function(id) {
        return document.getElementById(id);
    }
    if (event == undefined || event == null) {
        event = "submit";
    }
    this.IsValidator = false;
    var base = this;
    var form = $$(formid);
    var validArr = new Array();
    var validObjTag = "v_";
    //绑定验证控件的Class属性   
    var spans = document.getElementsByTagName("span");
    for (var i = 0; i < spans.length; i++) {
        if (spans[i].id.indexOf(validObjTag) != -1)
            spans[i].className = "validator";
    }
    //绑定提交事件
    addEvent(form, event, function() {
        base.IsValidator = base.valid(true);
        return base.IsValidator;
    }, "Validator" + event);

    //验证控件对应的ID   
    function validObjID(id) {
        return validObjTag + id;
    }
    //验证控件左边的对象内容
    function validName(id) {

        try {
            var txt = $($$(id).parentNode.parentNode.firstChild).prev();
            var result = txt[0].innerHTML.replace(':', '');
            result = urlHelp.MyReplace(result, ' ', '');
            result = urlHelp.MyReplace(result, '\n', '');
            return result;
        } catch (e) {
            return null; //txt.parentNode.previousSibling.innerHTML.replace(':', '');
        }
    }
    //绑定验证事件
    this.bind = function(id, title, eventArr, afterFun) {
        if ($$(id)) {
            if (!$$(validObjID(id))) {
                var valid = validObjID(id);
                var span = document.createElement("span");
                span.setAttribute("id", valid);
                span.setAttribute("class", "validator");
                $$(id).insertAdjacentElement("afterEnd", span);
                //alert("验证控件(id=" + validObjID(id) + ")不存在!");   
            }
            var count;
            validArr.push(new Array(id, title, eventArr, afterFun));
            addEvent($$(id), "blur", function() {
                var result = true;
                for (var i = 0; i < eventArr.length; i++) {
                    result = base.doValid(id, title, eventArr[i][0], eventArr[i][1], eventArr[i][2]);
                    if (!result) {
                        break;
                    }
                }
                if (afterFun != null && afterFun != undefined && result) {
                    afterFun($$(id), $$(validObjID(id)));
                }
            });
        }
    }
    //所有对象的验证事件   
    this.valid = function(showAlert) {
        var pass = true;
        for (var i = 0; i < validArr.length; i++) {
            var result = false;
            for (var j = 0; j < validArr[i][2].length; j++) {
                result = base.doValid(validArr[i][0], validArr[i][1], validArr[i][2][j][0], validArr[i][2][j][1], validArr[i][2][j][2]);
                if (!result) {
                    pass = false;
                    //显示验证提示
                    if (showAlert == true) {
                        var msg = validArr[i][2][j][1];
                        if (msg == "*") {
                            msg = "不得为空";
                        }
                        if (msg == "**") {
                            msg = "必选";
                        }
                        var show = validArr[i][1]; //validName(validArr[i][0]);
                        if (show != null) {
                            $$(validArr[i][0]).focus();
                            ValidatorAlert("【" + show + "】" + msg);
                            return pass;
                        }
                    }
                    break;
                }
            }
            var afterFun = validArr[i][3];
            if (afterFun != null && afterFun != undefined && result) {
                afterFun($$(validArr[i][0]), $$(validObjID(validArr[i][0])));
            }
        }
        return pass;
    }
    //一个对象的验证事件
    this.doValid = function(id, title, type, msg, reg) {
        if (msg == "*")
            msg = "*";
        if (msg == "**")
            msg = "*";
        switch (type) {
            case "empty": //为空
                return writeMsg(id, msg, ($$(id).value == ""));
                break;
            case "regular": //正则验证   
                return writeMsg(id, msg, ($$(id).value != "" && !reg.test($$(id).value)));
                break;
            case "contrast": //比较
                return writeMsg(id, msg, ($$(id).value != $$(reg).value));
                break;
            case "greater": //大于
                var bvalue = $$(id).value.length > 0 ? parseInt($$(id).value) : 0;
                var svalue = $$(reg).value.length > 0 ? parseInt($$(reg).value) : 0;
                return writeMsg(id, msg, (bvalue > svalue));
                break;
            case "smaller": //小于
                var xvalue = $$(id).value.length > 0 ? parseInt($$(id).value) : 0;
                var nvalue = $$(reg).value.length > 0 ? parseInt($$(reg).value) : 0;
                return writeMsg(id, msg, (xvalue < nvalue));
                break;
            case "max": //最大值
                return writeMsg(id, msg, ($$(id).value > reg));
                break;
            case "min": //最小值
                return writeMsg(id, msg, ($$(id).value < reg));
                break;
            case "number": //数字
                reg = /^\d+$/;
                return writeMsg(id, msg, ($$(id).value != "" && !reg.test($$(id).value)));
                break;
            case "double": //数字
                reg = /^\d+(\.\d*)?$/;
                return writeMsg(id, msg, ($$(id).value != "" && !reg.test($$(id).value)));
                break;
            case "maxlen":
                if (reg < 0) {
                    reg = 0;
                }
                var reg2 = new RegExp('^.{0,' + reg + '}$');
                if (msg == null || msg == "") {
                    msg = "超过最大长度" + reg;
                }
                return writeMsg(id, msg, ($$(id).value != "" && !reg2.test($$(id).value)));
                break;
            case "minlen":
                if (reg < 0) {
                    reg = 0;
                }
                var reg2 = new RegExp('^.{' + reg + ',2147483647}$');
                if (msg == null || msg == "") {
                    msg = "最小长度不得少于" + reg;
                }
                return writeMsg(id, msg, ($$(id).value != "" && !reg2.test($$(id).value)));
                break;
            //在此添加别的判断事件                                                                                                  
        }
    }
    //写出错误信息
    function writeMsg(id, msg, result) {
        $$(validObjID(id)).style.color = 'red';
        if (result) {
            $$(validObjID(id)).innerHTML = msg;
            return false;
        } else {
            //$$(validObjID(id)).style.color = 'green';
            $$(validObjID(id)).innerHTML = '';
            return true;
        }
    }
}



调用方式

$(document).ready(function() {
            var vld = new Validator("btn_login", "click");
            vld.bind("txt_username", "用户名", [["empty", "*"]]);
            vld.bind("txt_password", "密码", [["empty", "*"]]);
            vld.valid();
            //绑定提交事件
            addEvent(document.getElementById("btn_login"), "click", function() {
            if (vld.IsValidator) {
                    login();
                }
            },'btn_login_onchick');
        })



1楼u011999128昨天 13:31
您好,我看您09年的时候就开始做短信平台业务了,不知道您现在还在做这个吗?
  相关解决方案