先新建一个js文件 将下边代码拷贝其中,保存 待后边使用
/****
需要在jquery框架下运行,并却位置需放在jquery脚本文件之后
为输入框加入class类即可
null:不能为空
number:验证数字
email:验证Email
phone:验证电话
int:验证整型
zip:邮编
检查数据:Verification() 通过返回ture;否则返回true
*/
//方法体
var yoo ={
    //消息框
    msgbox: "<div id='dvPromptMsg' style='position: fixed;top:30%;left:40%;cursor: default;width: auto;height: auto;max-width: 500px;padding: 6px 13px 6px 13px;text-align: center;vertical-align: middle;border: 1px solid Green;font-size: 13px;letter-spacing: 1px;color: Green;font-weight: bold;background-color: #EDF7FF;display: none;z-index: 9999999;_position: absolute;_top: expression((ff=document.documentElement.clientHeight/2 + document.documentElement.scrollTop - this.offsetHeight/2)+ 'px' ););display:none;'></div>",
    //提示源
    errormsg: { "gthan0": "输入值需要大于0", "null": "不能为空!", "number": "数字格式有误!", "email": "Email格式有误!", "phone": "电话号码格式有误!", "int": "整型格式有误!", "zip": "邮编格式有误!" },
    //正则表达示源
    regsource: {
        "number": /^[0-9-.]*$/,
        "email": /^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT)$/,
        "phone": /(^[0-9]{3,4}\-[0-9]{7,8}\-[0-9]{3,4}$)|(^[0-9]{3,4}\-[0-9]{7,8}$)|(^[0-9]{7,8}\-[0-9]{3,4}$)|(^[0-9]{7,15}$)/,
        "int": new RegExp("^\s*[+-]?[0-9]+\s*$"),
        "zip": new RegExp("\d{6}"),
        "null": new RegExp("^[.*]"),
        "gthan0": /^[0-9.]*$/
    },
    //检测方法
    checkfunc: function (jq, keycode, eventmake) {
        //得到错误消息
        var errormsg = $.trim(jq.attr("msgname"));
        var reg = yoo.regsource[keycode], errormsg = (errormsg == "" ? "" : errormsg + ",") + yoo.errormsg[keycode];
        //为空检测
        if (keycode == "null") {
            if ($.trim(jq.val()) == "") { jq.attr("title", errormsg); if (!eventmake) yoo.alertmsg(errormsg); return false; }
            jq.attr("title", "");
            return true;
        }
        if ($.trim(jq.val()) == "") return true;
        if (!reg.exec($.trim(jq.val()))) {
            jq.css("color", "red");
            if ($("#errorsource").size() == 0)
                $("body").append('<style type="text/css" id="styleError"> .errorsource{background-position:bottom; background-image:url("/Images/blx.gif"); background-repeat:repeat-x;}</style>');
            jq.addClass("errorsource");
            yoo.alertmsg(errormsg);
            jq.select();
            jq.focus();
            return false;
        }
        jq.removeClass("errorsource");
        jq.css("color", "");
        jq.attr("title", "");
        return true;
    },
    //消息提示
    alertmsg: function (msg) {
                var oprompt = $("#dvPromptMsg");
                if (oprompt.size() == 0) { $("body").append(yoo.msgbox); oprompt = $("#dvPromptMsg"); }
                oprompt.html(msg);
                oprompt.show();
                setTimeout(function () { oprompt.fadeOut("fast") }, "2000");
        //if ($("#dvmsg").size() == 0)
        //js.alert(msg, null, 1);
       // alert(msg);
    },
    //区域添加验证方法
    specify: function (doms) {
        doms = $(doms);
        for (key in yoo.regsource) {
            var modes = doms.find("." + key);
            if (modes.size() == 0) continue;
            modes.blur(function () {
                var keycodes = $(this).attr("class").split(" ");
                for (var i = 0; i < keycodes.length; i++) {
                    if (!yoo.regsource[keycodes[i]]) continue;
                    if (!yoo.checkfunc($(this), keycodes[i], 1)) return;
                }
            });
        }
    },
    //指定区域验证
    specifyVerif: function (doms) {
        //检查错误源
        var doms = $(doms), oerror = null;
        for (keycode in yoo.regsource) {
            doms.find("." + keycode).each(function () { if (!oerror && !yoo.checkfunc($(this), keycode)) oerror = this; });
            if (oerror) break;
        }
        //检查输入字符串最大长度
        if (!oerror) {
            doms.find(".limit[maxlength]").each(function () {
                var sumlength = parseInt($(this).attr("maxlength"));
                var inputlength = this.value.length
                if (!oerror && inputlength > sumlength) {
                    oerror = $(this);
                    var msgname = $.trim(oerror.attr("msgname"));
                    yoo.alertmsg((msgname == "" ? "" : msgname + ",") + "可输入" + sumlength + "个字符,已超出" + (inputlength - sumlength) + "个字符");
                }
            });
        }
        //检查输入字符串最小长度
        if (!oerror) {
            doms.find("[minlength]").each(function () {
                var minlength = parseInt($(this).attr("minlength"));
                var inputlength = this.value.length
                if (!oerror && inputlength < minlength) {
                    oerror = $(this);
                    var msgname = $.trim(oerror.attr("msgname"));
                    yoo.alertmsg((msgname == "" ? "" : msgname + ",") + "最小输入" + minlength + "个字符,还需输入" + (minlength - inputlength) + "个字符");
                }
            });
        }

        if (!oerror) return true;

        //滑动到错误源
        (function ($) { var o = $.scrollTo = function (a, b, c) { o.window().scrollTo(a, b, c) }; o.defaults = { axis: 'y', duration: 1 }; o.window = function () { return $($.browser.safari ? 'body' : 'html') }; $.fn.scrollTo = function (l, m, n) { if (typeof m == 'object') { n = m; m = 0 } n = $.extend({}, $.scrollTo.defaults, n); m = m || n.speed || n.duration; n.queue = n.queue && n.axis.length > 1; if (n.queue) m = Math.ceil(m / 2); n.offset = j(n.offset); n.over = j(n.over); return this.each(function () { var a = this, b = $(a), t = l, c, d = {}, w = b.is('html,body'); switch (typeof t) { case 'number': case 'string': if (/^([+-]=)?\d+(px)?$/.test(t)) { t = j(t); break } t = $(t, this); case 'object': if (t.is || t.style) c = (t = $(t)).offset() } $.each(n.axis.split(''), function (i, j) { var P = j == 'x' ? 'Left' : 'Top', p = P.toLowerCase(), k = 'scroll' + P, e = a[k], D = j == 'x' ? 'Width' : 'Height', f = D.toLowerCase(); if (c) { d[k] = c[p] + (w ? 0 : e - b.offset()[p]); if (n.margin) { d[k] -= parseInt(t.css('margin' + P)) || 0; d[k] -= parseInt(t.css('border' + P + 'Width')) || 0 } d[k] += n.offset[p] || 0; if (n.over[p]) d[k] += t[f]() * n.over[p] } else d[k] = t[p]; if (/^\d+$/.test(d[k])) d[k] = d[k] <= 0 ? 0 : Math.min(d[k], h(D)); if (!i && n.queue) { if (e != d[k]) g(n.onAfterFirst); delete d[k] } }); g(n.onAfter); function g(a) { b.animate(d, m, n.easing, a && function () { a.call(this, l, b) }) }; function h(D) { var b = w ? $.browser.opera ? document.body : document.documentElement : a; return b['scroll' + D] - b['client' + D] } }) }; function j(a) { return typeof a == 'object' ? a : { top: a, left: a} } })(jQuery);
        $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body');
        $body.animate({ scrollTop: $(oerror).offset().top - 200 }, 400, function () { oerror.select(); });
        return false;
    },
    //验证页面
    Verification: function () { return yoo.specifyVerif("body"); },
    //初始化页面
    init: function () { yoo.specify("body") }
};
//加载验证项
$(document).ready(function () { yoo.init(); });
View Code

使用方法:

 //先引用jQuery
//在引用刚刚创建的js文件 $(function () { ShowMsg();//msg提示实例化 }) function Submit() { if (!yoo.specifyVerif("#checkDiv,#cgzjly")) { return;    //验证失败不提交表单 } alert("通过验证");
     //执行后边的代码 }
//html代码
<div id="checkDiv">
<input class="email" msg="输入email" />
<input msg="电话号码" />
<input class="null" minlength="3" maxlength="5" />
</div>
View Code

 

 

//效果如下:

 

posted on 2018-06-20 12:56  许一朵岁月  阅读(571)  评论(0编辑  收藏  举报