JS验证框架xValidate 7.01(20090830)

一想起验证,“头痛”,“麻烦”?费了点力气,一周时间终于写完了验证框架。纯js,以后验证轻松了。

不想看代码的朋友直接看最后的示例好了。

 

//验证框架基础类

var xValidate = {
    promptValidate: true,
    tipCss: null,
    validateState: 0,
    errObjSummary: null,
    errTipSummary: null,
    tipFormat: null,
    $Tag: function(n) { return document.getElementsByTagName(n); },
    init: function(promptvalidate, tipcss, tipformat) {
        xValidate.promptValidate = promptvalidate;
        xValidate.tipFormat = tipformat || "{num}.{tip}/n/r";
        xValidate.tipCss = tipcss;
        if (xValidate.promptValidate) {
            var vs;
            var inputs = xValidate.$Tag("input");
            for (var i = 0; i < inputs.length; i++) {
                vs = inputs[i].getAttribute("validateclass") || inputs[i].getAttribute("validatestyle");
                if (vs && vs.length > 0)
                    addEvent(inputs[i], "blur", xValidate.xValidatingOne);
            }
            inputs = xValidate.$Tag("textarea");
            for (var i = 0; i < inputs.length; i++) {
                vs = inputs[i].getAttribute("validateclass") || inputs[i].getAttribute("validatestyle");
                if (vs && vs.length > 0)
                    addEvent(inputs[i], "blur", xValidate.xValidatingOne);
            }
            inputs = xValidate.$Tag("select");
            for (var i = 0; i < inputs.length; i++) {
                vs = inputs[i].getAttribute("validateclass") || inputs[i].getAttribute("validatestyle");
                if (vs && vs.length > 0)
                    addEvent(inputs[i], "change", xValidate.xValidatingOne);
            }
        }
    },
    xValidatingAll: function() {
        xValidate.validateState = 2;
        xValidate.errObjSummary = new Array();
        xValidate.errTipSummary = new Array();
        var vs;
        var vr = true;
        var inputs = new Array();
        var tmps = xValidate.$Tag("input");
        for (var i = 0; i < tmps.length; i++) {
            vs = tmps[i].getAttribute("validatestyle") || tmps[i].getAttribute("validateclass");
            if (vs && vs.length > 0)
                inputs.push(tmps[i]);
        }
        tmps = xValidate.$Tag("select");
        for (var i = 0; i < tmps.length; i++) {
            vs = tmps[i].getAttribute("validatestyle") || tmps[i].getAttribute("validateclass");
            if (vs && vs.length > 0)
                inputs.push(tmps[i]);
        }
        tmps = xValidate.$Tag("textarea");
        for (var i = 0; i < tmps.length; i++) {
            vs = tmps[i].getAttribute("validatestyle") || tmps[i].getAttribute("validateclass");
            if (vs && vs.length > 0)
                inputs.push(tmps[i]);
        }
        for (var i = 0; i < inputs.length; i++) {
            if (!xValidate.xValidatingOne(inputs[i]))
                vr = false;
        }
        if (!vr) {
            if (xValidate.errTipSummary.length > 0) {
                var tiphtml = "";
                for (var i = 0; i < xValidate.errTipSummary.length; i++) {
                    tiphtml += xValidate.tipFormat.replace(/{tip}/g, xValidate.errTipSummary[i]).replace(/{num}/g, i + 1);
                }
                xValidate.alertHandle(tiphtml, xValidate.errObjSummary[0]);
            }
        }
        xValidate.validateState = 0;
        return vr;
    },
    xValidatingOne: function(obj, vt) {
        if (xValidate.validateState == 0)
            xValidate.validateState = 1;
        if (!obj.tagName)
            obj = obj.srcElement ? obj.srcElement : obj.target;
        var vs, vc, v, min, max, vr;
        vs = obj.getAttribute("validatestyle");
        vc = obj.getAttribute("validateclass");
        if (vs && vs.length > 0 && vs.charAt(0) == "[")
            vs = Json.decode(vs);
        if (vc && vc.length > 0)
            vc = xValidate.templateClass[vc.split("(")[0]];
        if (typeof vt == "string") {
            if (vt.length > 0 && vt.charAt(0) == "[")
                vt = Json.decode(vt);
            else
                vt = xValidate.templateClass[vt.split("(")[0]];
        }
        if ((!vs || vs.length == 0) && (!vc || vc.length == 0) && (!vt || vt.length == 0))
            return false;
        var vo = [];
        var tmpv;
        for (var j = 0; j < xValidate.validateTypes.length; j++) {
            tmpv = xValidate.findValidateItme(vt, xValidate.validateTypes[j]);
            if (tmpv == null)
                tmpv = xValidate.findValidateItme(vs, xValidate.validateTypes[j]);
            if (tmpv == null)
                tmpv = xValidate.findValidateItme(vc, xValidate.validateTypes[j]);
            if (tmpv != null)
                vo.push(tmpv);
        }
        if (!vo || vo.length == 0)
            return false;
        for (var j = 0; j < vo.length; j++) {
            if (vo[j].validating) {
                if (!vo[j].validating(obj, vo[j]))
                    continue;
            }
            if (obj.getAttribute("required") && obj.getAttribute("required").toLowerCase() == "false" && obj.value.replace(/(^/s*)|(/s*$)/g, "").length == 0)
                continue;
            switch (vo[j].type) {
                case "empty":
                    vr = obj.value.replace(/(^/s*)|(/s*$)/g, "").length == 0;
                    if (vo[j].mirror ? !vr : vr) {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    else
                        xValidate.xValidated(obj, vo[j], true);
                    break;
                case "equal":
                    v = (vo[j].value.length > 10 && vo[j].value.indexOf("javascript:") == 0) ? eval(vo[j].value.substr(11)) : vo[j].value;
                    vr = v == obj.value;
                    if (vo[j].mirror ? !vr : vr)
                        xValidate.xValidated(obj, vo[j], true);
                    else {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    break;
                case "include":
                    v = (vo[j].value.toString().indexOf("javascript:") == 0) ? eval(vo[j].value.substr(11)) : vo[j].value;
                    vr = true;
                    for (var i = 0; i < v.length; i++) {
                        if (obj.value.indexOf(v[i]) != -1) {
                            vr = false;
                            break;
                        }
                    }
                    if (vo[j].mirror ? !vr : vr)
                        xValidate.xValidated(obj, vo[j], true);
                    else {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    break;
                case "length":
                    v = obj.value.length;
                    min = (vo[j].min.toString().length > 10 && vo[j].min.toString().indexOf("javascript:") == 0) ? eval(vo[j].min.substr(11)) : parseInt(vo[j].min);
                    max = (vo[j].max.toString().length > 10 && vo[j].max.toString().indexOf("javascript:") == 0) ? eval(vo[j].max.substr(11)) : parseInt(vo[j].max);
                    vr = v < min || v > max;
                    if (vo[j].mirror ? !vr : vr) {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    else
                        xValidate.xValidated(obj, vo[j], true);
                    break;
                case "byte":
                    v = xValidate.getLengthByByte(obj.value);
                    min = (vo[j].min.toString().length > 10 && vo[j].min.toString().indexOf("javascript:") == 0) ? eval(vo[j].min.substr(11)) : parseInt(vo[j].min);
                    max = (vo[j].max.toString().length > 10 && vo[j].max.toString().indexOf("javascript:") == 0) ? eval(vo[j].max.substr(11)) : parseInt(vo[j].max);
                    vr = v < min || v > max;
                    if (vo[j].mirror ? !vr : vr) {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    else
                        xValidate.xValidated(obj, vo[j], true);
                    break;
                case "number":
                    v = parseFloat(obj.value);
                    min = (vo[j].min.toString().length > 10 && vo[j].min.toString().indexOf("javascript:") == 0) ? eval(vo[j].min.substr(11)) : parseFloat(vo[j].min);
                    max = (vo[j].max.toString().length > 10 && vo[j].max.toString().indexOf("javascript:") == 0) ? eval(vo[j].max.substr(11)) : parseFloat(vo[j].max);
                    vr = isNaN(v) || isNaN(min) || isNaN(max) || v < min || v > max;
                    if (vo[j].mirror ? !vr : vr) {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    else
                        xValidate.xValidated(obj, vo[j], true);
                    break;
                case "digit":
                    v = parseFloat(obj.value);
                    min = (vo[j].min.toString().length > 10 && vo[j].min.toString().indexOf("javascript:") == 0) ? eval(vo[j].min.substr(11)) : parseInt(vo[j].min);
                    max = (vo[j].max.toString().length > 10 && vo[j].max.toString().indexOf("javascript:") == 0) ? eval(vo[j].max.substr(11)) : parseInt(vo[j].max);
                    var idx = v.toString().indexOf(".");
                    idx = (idx == -1) ? 0 : obj.value.length - idx - 1;
                    vr = isNaN(v) || isNaN(min) || isNaN(max) || isNaN(idx) || idx < min || idx > max;
                    if (vo[j].mirror ? !vr : vr) {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    else
                        xValidate.xValidated(obj, vo[j], true);
                    break;
                case "int":
                    v = parseInt(obj.value);
                    min = (vo[j].min.toString().length > 10 && vo[j].min.toString().indexOf("javascript:") == 0) ? eval(vo[j].min.substr(11)) : parseInt(vo[j].min);
                    max = (vo[j].max.toString().length > 10 && vo[j].max.toString().indexOf("javascript:") == 0) ? eval(vo[j].max.substr(11)) : parseInt(vo[j].max);
                    vr = isNaN(v) || isNaN(min) || isNaN(max) || v < min || v > max;
                    if (vo[j].mirror ? !vr : vr) {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    else
                        xValidate.xValidated(obj, vo[j], true);
                    break;
                case "date":
                    v = Date.formString(obj.value);
                    min = (vo[j].min.toString().length > 10 && vo[j].min.toString().indexOf("javascript:") == 0) ? eval(vo[j].min.substr(1)) : Date.formString(vo[j].min);
                    max = (vo[j].max.toString().length > 10 && vo[j].max.toString().indexOf("javascript:") == 0) ? eval(vo[j].max.substr(1)) : Date.formString(vo[j].max);
                    vr = isNaN(v) || isNaN(min) || isNaN(max) || v < min || v > max;
                    if (vo[j].mirror ? !vr : vr) {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    else
                        xValidate.xValidated(obj, vo[j], true);
                    break;
                case "regex":
                    vr = vo[j].pattern.test(obj.value);
                    if (vo[j].mirror ? !vr : vr)
                        xValidate.xValidated(obj, vo[j], true);
                    else {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    break;
                case "function":
                    vr = vo[j].handle(obj, vo[j]);
                    if (vo[j].mirror ? !vr : vr)
                        xValidate.xValidated(obj, vo[j], true);
                    else {
                        xValidate.xValidated(obj, vo[j], false);
                        return false;
                    }
                    break;
            }
        }
        if (xValidate.promptValidate) {
            v = $((obj.name || obj.id) + "_tipdiv");
            if (v)
                document.body.removeChild(v);
        }
        v = obj.getAttribute("validatecorrectclass");
        if (v)
            obj.className = v;
        if (xValidate.validateState == 1)
            xValidate.validateState = 0;
        return true;
    },
    xValidated: function(obj, voj, vr) {
        if (!vr) {
            var tip = voj.tip.replace(/%value%/g, obj.value).replace(/%length%/g, obj.value.length).replace(/%byte%/g, xValidate.getLengthByByte(obj.value));
            var ech = obj.getAttribute("validateclass");
            if (ech && ech.indexOf("(") != -1)
                ech = ech.split("(")[1].replace(//)$/, "");
            else
                ech = "";
            tip = tip.replace(/{x}/g, ech);
            if (xValidate.promptValidate) {
                var v = $((obj.name || obj.id) + "_tipdiv");
                if (v)
                    document.body.removeChild(v);
                switch (voj.tipmode) {
                    case undefined:
                    default:
                    case 1:
                        if (!$((obj.name || obj.id) + "_tipdiv")) {
                            var xy = getPos(obj);
                            var tipDiv = document.createElement("div");
                            tipDiv.id = (obj.name || obj.id) + "_tipdiv";
                            tipDiv.style.position = "absolute";
                            tipDiv.style.zIndex = "255";
                            tipDiv.className = obj.getAttribute("validatetipclass") || xValidate.tipCss;
                            tipDiv.innerHTML = tip;
                            document.body.appendChild(tipDiv);
                            var vx = parseInt(obj.getAttribute("validatetipx"));
                            var vy = parseInt(obj.getAttribute("validatetipy"));
                            tipDiv.style.left = xy.x + (isNaN(vx) ? 0 : vx) + obj.offsetWidth + "px";
                            tipDiv.style.top = xy.y + (isNaN(vy) ? 0 : vy) - tipDiv.offsetHeight / 2 + obj.offsetHeight / 2 + "px";
                        }
                        else
                            $((obj.name || obj.id) + "_tipdiv").innerHTML = tip;
                        break;
                    case 0:
                    case 2: break;
                    case 3: $(voj.controlid).innerHTML = tip; break;
                    case 4: $(voj.controlid).value = tip; break;
                    case 5: xValidate.alertHandle(tip); break;
                }
            }
            if (xValidate.validateState == 2) {
                if (!voj.tipmode || voj.tipmode != 0)
                    xValidate.errTipSummary.push(tip);
                xValidate.errObjSummary.push(obj);
            }
            var vfc = obj.getAttribute("validatefailedclass");
            if (vfc)
                obj.className = vfc;
        }
        if (voj.validated)
            voj.validated(obj, vr);
        if (xValidate.validateState == 1)
            xValidate.validateState = 0;
    },
    findValidateItme: function(vo, type) {
        if (!vo || vo.length == 0)
            return null;
        if (typeof vo == "string")
            vo = Json.decode(vo);
        for (var i = 0; i < vo.length; i++) {
            if (vo[i].type == type)
                return vo[i];
        }
        return null;
    },
    getLengthByByte: function(s) {
        if (!s)
            return 0;
        var c = 0;
        for (var i = 0; i < s.length; i++)
            c += (s.charCodeAt(i) < 0xFF) ? 1 : 2;
        return c;
    },
    alertHandle: function(tip, focusObj) {
        alert(tip);
        if (focusObj) {
            if (focusObj.tagName.toLowerCase() == "select")
                focusObj.focus();
            else
                focusObj.select();
        }
    },
    getCurrentStyle: function(o) {
        return o.currentStyle || document.defaultView.getComputedStyle(o, null);
    },
    validateTypes: new Array("empty", "equal", "include", "length", "byte", "number", "digit", "int", "date", "regex", "function"),
    templateClass: {
        username: [{ type: "empty", tip: "请填写用户名称" }, { type: "byte", min: 4, max: 20, tip: "用户名应为4~20个字符(一个汉字算两个字符)" }, { type: "regex", pattern: /^([a-zA-Z]/w{2,18}[a-zA-Z0-9]|[/u4E00-/u9FA5][/u4E00-/u9FA5a-zA-Z0-9]{1,9})$/, tip: "您填写的用户名称包含特殊字符"}],
        password: [{ type: "empty", tip: "请填写密码" }, { type: "length", min: 6, max: 16, tip: "请输入6~16个字符"}],
        verify: [{ type: "empty", tip: "请填写确认密码" }, { type: "equal", value: "javascript:$('txtPassword').value", tip: '您两次填写的密码不一致。'}],
        vcode: [{ type: "empty", tip: "请按照图片显示填写验证号码,如看不清请点击图片更换" }, { type: "length", min: 4, max: 4, tip: "您填写的验证号码不正确"}],
        address: [{ type: "empty", tip: "请填写{x}详细地址" }, { type: "length", min: 2, max: 200, tip: "您填写的{x}详细地址无效"}],
        postcode: [{ type: "empty", tip: "请填写{x}邮政编码" }, { type: "regex", pattern: /^/d{6}$/, tip: "您填写的{x}邮政编码无效"}],
        realname: [{ type: "empty", tip: "请填写{x}真实姓名" }, { type: "regex", pattern: /^[a-zA-Z]/w{2,18}[a-zA-Z0-9]|[/u4E00-/u9FA5]{2,5}$/, tip: "请填写正确的{x}真实姓名"}],
        creditcard: [{ type: "empty", tip: "请填写{x}卡号" }, { type: "regex", pattern: /^[0-9]([0-9]|[/-/s]){11,20}[0-9]$/, tip: "您填写的{x}卡号格式不正确"}],
        quantity: [{ type: "empty", tip: "请填写{x}数量" }, { type: "int", min: 1, max: 9999, tip: "您填写的{x}数量无效"}],
        url: [{ type: "empty", tip: "请填写{x}地址" }, { type: "regex", pattern: /^(http|https)?:[A-Za-z0-9]+/.[A-Za-z0-9]+[//=/?%/-&_~`@[/]/':+!]*([^<>/"/"])*$/, tip: "您填写的{x}地址格式无效"}],
        qq: [{ type: "empty", tip: "请填写{x}QQ号码" }, { type: "regex", pattern: /^[1-9]/d{4,8}$/, tip: "您填写的{x}QQ号码格式不正确"}],
        ip: [{ type: "empty", tip: "请填写{x}IP地址" }, { type: "regex", pattern: /^(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])/.(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])/.(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])/.(/d{1,2}|1/d/d|2[0-4]/d|25[0-5])$/, tip: "您填写的{x}IP地址格式无效"}],
        email: [{ type: "empty", tip: "请填写{x}电子邮箱地址" }, { type: "length", min: 8, max: 50, tip: "您填写的{x}电子邮箱地址长度无效" }, { type: "regex", pattern: /^/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*$/, tip: "您填写的{x}电子邮箱格式不正确"}],
        idcard: [{ type: "empty", tip: "请填写{x}身份证号码" }, { type: "function", handle: checkIdCard, tip: "您填写的{x}身份证号码无效"}],
        money: [{ type: "empty", tip: "请填写{x}金额" }, { type: "number", min: 0, max: 99999999, tip: "您填写的{x}金额无效" }, { type: "dight", min: 0, max: 2, tip: "{x}金额最多可以填写2位小数"}],
        mobile: [{ type: "empty", tip: "请填写{x}手机号码" }, { type: "regex", pattern: /^(((13[0-9]{1})|15[0-9]{1}|18[0-9]{1})+/d{8})$/, tip: "您填写的{x}手机号码格式不正确"}],
        telephone: [{ type: "empty", tip: "请填写{x}座机电话号码" }, { type: "regex", pattern: /^([/d-+]{4,20})$/, tip: "您填写的{x}座机电话号码不正确"}],
        fax: [{ type: "empty", tip: "请填写{x}传真号码" }, { type: "regex", pattern: /^([/d-+]{4,20})$/, tip: "您填写的{x}传真号码不正确"}],
        date: [{ type: "empty", tip: "请填写{x}日期。" }, { type: "date", min: new Date(1900, 0, 1), max: new Date(2079, 5, 6), tip: "您填写的{x}日期无效"}]
    }
};

//验证身份证的方法,验证模板中用到了

function checkIdCard(sNo) { if (sNo == null) return false; sNo = sNo.value.toString(); if (sNo.length == 18) { var a, b, c; if (isNaN(sNo.substr(0, 17))) { return false; } a = parseInt(sNo.substr(0, 1)) * 7 + parseInt(sNo.substr(1, 1)) * 9 + parseInt(sNo.substr(2, 1)) * 10; a = a + parseInt(sNo.substr(3, 1)) * 5 + parseInt(sNo.substr(4, 1)) * 8 + parseInt(sNo.substr(5, 1)) * 4; a = a + parseInt(sNo.substr(6, 1)) * 2 + parseInt(sNo.substr(7, 1)) * 1 + parseInt(sNo.substr(8, 1)) * 6; a = a + parseInt(sNo.substr(9, 1)) * 3 + parseInt(sNo.substr(10, 1)) * 7 + parseInt(sNo.substr(11, 1)) * 9; a = a + parseInt(sNo.substr(12, 1)) * 10 + parseInt(sNo.substr(13, 1)) * 5 + parseInt(sNo.substr(14, 1)) * 8; a = a + parseInt(sNo.substr(15, 1)) * 4 + parseInt(sNo.substr(16, 1)) * 2; b = a % 11; if (b == 2) { c = sNo.substr(17, 1).toUpperCase(); } else { c = parseInt(sNo.substr(17, 1)); } switch (b) { case 0: if (c != 1) { return false; } break; case 1: if (c != 0) { return false; } break; case 2: if (c != "X") { return false; } break; case 3: if (c != 9) { return false; } break; case 4: if (c != 8) { return false; } break; case 5: if (c != 7) { return false; } break; case 6: if (c != 6) { return false; } break; case 7: if (c != 5) { return false; } break; case 8: if (c != 4) { return false; } break; case 9: if (c != 3) { return false; } break; case 10: if (c != 2) { return false }; } } else { if (isNaN(sNo)) { return false; } } switch (sNo.length) { case 15: if (checkDateTime(sNo.substr(6, 2) + '-' + sNo.substr(8, 2) + '-' + sNo.substr(10, 2))) { return true; } case 18: if (checkDateTime(sNo.substr(6, 4) + '-' + sNo.substr(10, 2) + '-' + sNo.substr(12, 2))) { return true; } } return false; }

 

//一些库方法

Date.fromString = function(str) { return new Date(Date.parse(str.replace(//-/g, '/'))); }
function $(id) { return document.getElementById(id); }
var Json = { encode: function(o) { var s = [], p = {}, c = ""; p.isArr = o instanceof Array; if (p.isArr) { p.l = "["; p.r = "]" } else { p.l = "{"; p.r = "}" }; for (k in o) { if (!p.isArr) c = '"' + k + '":'; else c = ""; switch (typeof (o[k])) { case "object": if (o[k] instanceof Object) c += arguments.callee(o[k]); else c += o[k]; break; case "string": c += '"' + o[k].replace("//", "").replace('"', '//"') + '"'; break; case "number": case "boolean": case "null": c += o[k]; break; default: continue }; s.push(c) }; return p.l + s.join(",") + p.r }, decode: function(str) { var k; try { k = eval('(' + str + ')'); return (typeof k == "object") ? k : '' } catch (e) { return '' } } };
function addEvent(oElement, sEvent, func) { if (oElement.addEventListener) { oElement.addEventListener(sEvent, func, false); } else if (oElement.attachEvent) { oElement.attachEvent("on" + sEvent, func); } else { oElement["on" + sEvent] = func; } }
function getEvent() { if (window.event) return window.event; var func = getEvent.caller; var arg0 = null; while (func != null) { arg0 = func.arguments[0]; if (arg0 && ((arg0.constructor == window.top.Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation))) return arg0; func = func.caller; } return null; }
function getSrcElement() { var e = getEvent(); return e.srcElement ? e.srcElement : e.target; }
function getPos(o) { var x = 0, y = 0; x -= (o.style.borderLeftWidth ? parseInt(o.style.borderLeftWidth) : 0); y -= (o.style.borderTopWidth ? parseInt(o.style.borderTopWidth) : 0); do { x += o.offsetLeft + (o.style.borderLeftWidth ? parseInt(o.style.borderLeftWidth) : 0); y += o.offsetTop + (o.style.borderTopWidth ? parseInt(o.style.borderTopWidth) : 0); o = o.offsetParent; } while (o)return { x: x, y: y }; }

 

验证框架使用说明和实例

验证框架由js静态类xValidate所封装。以下是该类介绍:
类名:xValidate
静态类,但需要使用前初始化。否则不会启用该页的验证框架。

标签声明规则:
1.任意input、select和textarea上可加此验证。
2.标签属性:
    a.validateclass:验证类名称。该值是验证模板类中的有效名称。可以写成以下2种形式:
        (1).validateclass="date" - 一般模板调用
        (2).validateclass="date(入住)" - 使用模板,并替换模板中tip属性里的{x}为“入住”
    b.validatestyle:值为验证样式,即json表达式。
    c.validatetipclass:为此控件设置弹出提示层样式类。
    d.required:是否为必填项,可以不声明此属性。如果为非必填项,那么当控件值为空时验证全部通过。值为true/false。
    e.validatefailedclass:验证失败时控件的样式。
    f.validatecorrectclass:验证成功时控件的样式。
    g.validatetipx:由于提示层的位置属性不可由样式控制(已屏蔽)。因此可以通过该属性调整提示层相对控件右上角的x坐标偏移。值为整数。
    h.validatetipy:通过该属性可以调整提示层相对控件右上角的y坐标偏移。值为整数。

包含属性:
promptValidate:值true或false。表示是否控件onblur(select为onchange)时进行验证
tipCss:值为任意字符串。表示提示层div的class名称。
templateClass:值为验证表达式。包含常用的验证模板类。
validateState:值为0、1或2。表示验证状态,0-无、1-单控件验证中、2-全部控件验证中。
errObjSummary:值为对象数组。失败控件的引用数组。(单控件验证时无效)
errTipSummary:值为字符串数组。失败提示数组。(单控件验证时无效)
validateTypes:值为数组。用于验证的有效type类型。(值必须是验证type类型列表中提供的值,默认全部有效)
tipFormat:值为字符串。表示多行提示时的每一条提示格式。默认为:"{num}.{tip}/n/r"

包含的方法:
init(promptvalidate, tipcss,tipformat):初始化并启用页面的验证框架(要执行验证的页面底部但在之前执行此函数)。promptvalidate:是否失去焦点自动提示,值true/false。tipcss:失去焦点时提示层div的样式。tipformat:提示语句的格式。
$Tag(n):通过tag名称获取元素集合。
xValidatingAll():触发验证页面上所有控件。返回true/false。
xValidatingOne(obj,vo):验证单一控件,obj为要验证的控件,vo为验证表达式或验证模板名称(可选)。返回true/false。
xValidated(obj, voj, vr):验证结束后执行的内部方法。
getLengthByByte(s):获取字符串的字节长度。
getCurrentStyle(o):获取元素的当前样式。
findValidateItme(vo,type):通过验证类型type查找验证规则。(没有返回null)
alertHandle(tip,focusObj):提示框提示方法的委托。tip为提示文本,focusObj为要焦点的控件。

验证json表达式语法:
1.以“[”开头,以“]”结尾。中间可包含一个或多个验证规则。
2.验证规则格式是以“{”开头,以“}”结尾,每个规则用“,”隔开。
3.验证规则里面的细则使用“:”分割的键值对表示,并且每对细则间使用“,”隔开。形如“aaa:bbb,ccc:ddd”
4.aaa和ccc为细则名称。bbb和ddd为细则值,细则值可以是字符串,数字,正则表达式,方法,日期对象,布尔值等任意变量或对象。(注意字符串值需要加单引号)

示例:验证Email的验证json表达式:
  1. [{ type: 'empty', tip: '请输入电子邮箱地址' }, { type: 'length', min: 5, max: 50, tip: '您输入的电子邮箱地址长度无效' }, { type: 'regex', pattern: /^/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*$/, tip: '请输入正确的电子邮箱地址'}]
复制代码
验证json表达式属性定义:
1.type:验证类型,必填。指示此细则如何验证。值为字符串常量。
2.tip:提示内容,必填。指示验证失败后提示给用户的文字信息。值为字符串。(可包含%value%,%length%,%byte%三种动态变量分别代表值,长度和字节数)
3.value:验证对比值,非必填。值可能为字符串、数字或数组或以“javascript:”开头的js字符串。
4.min:验证对比最小值,非必填。值为整数或以“javascript:”开头的js字符串。
5.max:验证对比最大值,非必填。值为整数或以“javascript:”开头的js字符串。
6.pattern:验证正则内容,非必填。值为正则表达式。
7.handle:验证方法引用,非必填。方法原型:bool function(element, jsonObject) = 验证成功与否 function(要验证的控件对象,验证json表达式)。值为方法引用。
8.validating:验证前执行的方法引用,非必填。方法原型:bool function(element, jsonObject) = 是否取消本次验证的执行 function(要验证的控件对象,验证json表达式)。值为方法引用。
9.validated:验证后执行的方法引用,非必填。方法原型:void function(element,result) = function(要验证的控件对象,验证成功与否结果)。值为方法引用。
10.mirror:指示验证结果是否取反。非必填。值为布尔值。
11.tipmode:提示模式
    undefined - 缺省提示,等同正常提示。
    0 - 隐藏提示 :无论在单控件验证还是全体验证提示时都不进行提示。
    1 - 正常提示。
    2 - 关闭即时提示。
    3 - 将提示内容填写到指定控件的innerHTML属性中。(需要指定controlid)
    4 - 将提示内容填写到指定控件的value属性中。(需要指定controlid)
    5 - 提示框方式。
12.controlid:相关控件ID。

验证细则中类型type的值列表:
1.empty:为空(指去除两端空格后为空字符串)则验证不通过,扩展属性:tip*,mirror
2.equal:不相等value则验证不通过,扩展属性:tip*,value*,mirror
3.include:包含value指定字符串数组中任何字符串时验证不通过。扩展属性:tip*,value*,mirror
4.length:长度超出范围则验证不通过。扩展属性:tip*,min*,max*,mirror
5.byte:字节超出范围则验证不通过。扩展属性:tip*,min*,max*,mirror
6.number:数字超出范围则验证不通过。扩展属性:tip*,min*,max*,mirror
7.digit:数字小数点后位数超出范围则验证不通过。扩展属性:tip*,min*,max*,mirror
8.int:整数超出范围则验证不通过。扩展属性:tip*,min*,max*,mirror
9.date:日期超出范围则验证不通过。扩展属性:tip*,min*,max*,mirror
10.regex:正则验证失败则验证不通过。扩展属性:tip*,pattern*,mirror
11.function:方法返回false则验证不通过。扩展属性:tip*,handle*,mirror

模板类名称:
username
password
verify
vcode
address
postcode
realname
creditcard
quantity
url
qq
ip
email
idcard
money
mobile
telephone
fax
date

示例:
  

你可能感兴趣的:(JS验证框架xValidate 7.01(20090830))