javascript比较实用方法:身份证验证、文本框设置不可空等等

var $ = document.getElementById;

//限制字数 onkeyup=""
function MaxSizeKeyUp(n) {
    var obj = event.srcElement;
    if (obj.value.length > n) {
        obj.value = obj.value.substr(0, n);
    }
}
//通过身份证号获取生日、年龄、性别
function getDateByIdCard(UUserCard,num){
   if(num==1){
       //获取出生日期
       birth=UUserCard.substring(6, 10) + "-" + UUserCard.substring(10, 12) + "-" + UUserCard.substring(12, 14);
    return birth;
   }
   if(num==2){
       //获取性别
       if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
           //男
     return "男";
       } else {
           //女
     return "女";
       }
   }
   if(num==3){
        //获取年龄
        var myDate = new Date();
        var month = myDate.getMonth() + 1;
        var day = myDate.getDate();
        var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
        if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
            age++;
        }
  return age;
 }
}

//验证只能输入浮点数字 onkeyup=""
function floatKeyUp(n, m) {
    var obj = event.srcElement;
    var reg;
    if (null == n || null == m) {
        reg = new RegExp("^\\d+(\\.\\d*)?$");
    }
    else {
        reg = new RegExp("^\\d{1," + n + "}(\\.\\d{0," + m + "})?$");
    }
    while (obj.value != '' && !(reg.test(obj.value))) {
        obj.value = obj.value.substr(0, obj.value.length - 1);
    }
}
//验证只能输入整型数字 onkeyup=""
function intKeyUp(n) {
    var obj = event.srcElement;
    var reg;
    if (null == n) {
        reg = new RegExp("^\\d*$");
    }
    else {
        reg = new RegExp("^\\d{1," + n + "}$");
    }
    while (obj.value != '' && !(reg.test(obj.value))) {
        obj.value = obj.value.substr(0, obj.value.length - 1);
    }
}
//验证输入正负浮点数字 onkeyup=""
function floatMinusKeyUp(n, m) {
    var obj = event.srcElement;
    var reg;
    if (null == n || null == m) {
        reg = new RegExp("^\\-(\\d+(\\.\\d*)?)?$");
    }
    else {
        reg = new RegExp("^\\-(\\d{1," + n + "}(\\.\\d{0," + m + "})?)?$");
    }
    while (obj.value != '' && !(reg.test(obj.value))) {
        obj.value = obj.value.substr(0, obj.value.length - 1);
    }
}
//验证输入正浮点数字 onkeyup=""
function floatMinusKey(n, m) {
    var obj = event.srcElement;
    var reg;
    if (null == n || null == m) {
        reg = new RegExp("^(\\d+(\\.\\d*)?)?$");
    }
    else {
        reg = new RegExp("^(\\d{1," + n + "}(\\.\\d{0," + m + "})?)?$");
    }
    while (obj.value != '' && !(reg.test(obj.value))) {
        obj.value = obj.value.substr(0, obj.value.length - 1);
    }
}

//年月验证 onkeyup=""
function DateKeyUp() {
    var obj = event.srcElement;
    if (obj.value.length == 2) {
        if (obj.value < "19") {
            obj.value = '20' + obj.value + '-';
        }
        else if (obj.value > "49") {
            obj.value = '19' + obj.value + '-';
        }
    }
    var reg = RegExp("^\\d{1,4}(\\-\\d{0,2})?$");
    while (obj.value != '' && !(reg.test(obj.value))) {
        obj.value = obj.value.substr(0, obj.value.length - 1);
    }
    if (obj.value.length == 4 && obj.value.substr(obj.value.length - 1) != '-') {
        obj.value += '-';
    }
}
//年月验证 onblur=""
function DateBlur() {
    var obj = event.srcElement;
    if (obj.value != "") {
        var reg = new RegExp(/^([0-9]{4}(\-){1}(([0]?[1-9]{1})|([1-9]{1})|([1]{1}[0-2]{1}))?)$/);
        if (!reg.test(obj.value)) {
            var msg = "日期格式有误,请核对!\r\n按[确定]修改,按[取消]清空";
            if (window.confirm(msg)) {
                obj.focus();
            }
            else {
                obj.value = "";
            }
        }
    }
}
//开始与结束时间比较验证 onpropertychange=""
function CheckDateSpan(startDateId, endDateId) {
    var obj = event.srcElement;
    if ($(startDateId).value != "" && $(endDateId).value != "" && $(startDateId).value > $(endDateId).value) {
        alert("开始日期不能大于结束日期!");
        if (obj.id == startDateId) {
            obj.value = $(endDateId).value;
        } else {
            obj.value = $(startDateId).value;
        }
        obj.focus();
    }
}


//电话号码验证 onblur="" telType-  空:移动电话或固定电话,1:移动电话 2:固定电话
function TelephonBlur(telType) {
    var obj = event.srcElement;
    if (obj.value != "") {
        reg = new RegExp(/(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/);
        if (telType == "1") {
            reg = new RegExp(/\d{11}/);
        } else if (telType == "2") {
            reg = new RegExp(/^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/);
        }
        if (!reg.test(obj.value)) {
            var msg = "电话号码格式有误,请核对!\r\n按[确定]修改,按[取消]清空";
            if (window.confirm(msg)) {
                obj.focus();
            }
            else {
                obj.value = "";
            }
        }
    }
}
//控制输入项目不为空, 控件需设置 nonull 、elementname 属性
function CheckNull() {
    //debugger;
    var objs = document.getElementsByTagName("input");
    if (!CheckNullByObjs(objs)) {
        return false;
    }
    var objs2 = document.getElementsByTagName("select");
    if (!CheckNullByObjs(objs2)) {
        return false;
    }
    var objs3 = document.getElementsByTagName("textarea");
    if (!CheckNullByObjs(objs3)) {
        return false;
    }
    return true;
}
//去掉前后空格
function Trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
function CheckNullByObjs(objs) {
    for (var i = 0; i < objs.length; i++) {
        if (objs[i].attributes["nonull"] != undefined && objs[i].attributes["nonull"].value == "true" && Trim(objs[i].value).toString() == "") {
            alert(objs[i].attributes["elementname"].value + "不能为空");
            objs[i].focus();
            return false;
        }
    }

    return true;
}

//打开模式网页对话框
function OpenModelWindow(URL, width, height) {
    if (width == null)
        width = 800;
    if (height == null)
        height = 600;
    if (getIEVersion() == 6) {
        height += 30;
    }
    if (URL.indexOf('?') == -1) {
        URL += '?__Rand=' + Math.random()
    }
    else {
        URL += '&__Rand=' + Math.random();
    }
    var result = window.showModalDialog(URL, window, "DialogWidth:" + width + "px;DialogHeight:" + height + "px;status:no;toolbar:no;menubar:no;location:no;scrollbars:yes;resizable:no;help:no;");
    return result;
}
//打开模式网页对话框(全屏)
function OpenModelFullScreen(URL) {
    var width = screen.width;
    var height = screen.height;
    OpenModelWindow(URL, width, height);
}

//打开新窗体
function OpenForm(bz, url, width, height) {
    var prileft = (screen.width - width) / 2;
    var pritop = (screen.height - height - 50) / 2;
    if (bz == 0) {//全屏
        window.open(url, 'TsUrl', 'fullscreen')
    }
    else if (bz == 1) {//无菜单,地址栏等
        var Win = window.open(url, "", 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + width + ', height=' + height + ',left=' + prileft + ',top=' + pritop);
    }
    else if (bz == 2) {//有菜单
        var Win = window.open(url, "", 'width=' + width + ', height=' + height + ', resizable=yes, scrollbars=yes, menubar=yes, status=yes');
    }
    else if (bz == 3) {//无菜单,地址栏,有滚动条等
        var Win = window.open(url, "", 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=' + width + ', height=' + height + ',left=' + prileft + ',top=' + pritop);
    }
    else if (bz == 4) {//无菜单,无地址栏,有滚动条,状态栏等
        var Win = window.open(url, "", 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=' + width + ', height=' + height + ',left=' + prileft + ',top=' + pritop);
    }
}

//全屏打开新窗体
function OpenFullWindow(strUrl) {
    var widthPx = screen.width;
    var lengthPx = screen.height;
    var strFeatures = "width=" + widthPx + ",height=" + lengthPx + ",scrollbars=1,status=1,center=1,resizable=0";
    var newwin = window.open(strUrl, "", strFeatures);  //strFormName

}

//判断ie版本
function getIEVersion() {
    //alert(navigator.userAgent);
    if (navigator.appName == "Microsoft Internet Explorer") {
        if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {
            return 8;
        }
        else if (navigator.userAgent.indexOf("MSIE 7.0") > 0) {
            return 7;
        }
        else {
            return 6;
        }
    }
}

//根据QueryString参数名称获取值 
function getQueryStringByName(name, strLocation) {

    if (strLocation == null) {
        strLocation = location;
    }
    var result = strLocation.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[1];
}

///验证身份证号是否合法
function CheckIdCard(cardTypeId) {
//    if (cardTypeId != null && document.getElementById(cardTypeId).value != '1') {
//        return true;
//    }
    var msg = "";
    var obj = event.srcElement;
    obj.value = obj.value.toUpperCase();
    var num = obj.value;
    if (num == "") {
        msg = "";
    }
    else if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
        msg = '输入的身份证号长度不对,或输入非法字符,请核对!';
    }
    else {
        //下面分别分析出生日期和校验位 
        var len, re;
        len = num.length;
        if (len == 15) {
            re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
            var arrSplit = num.match(re);
            //检查生日日期是否正确 
            var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
                msg = '输入的身份证号里出生日期不对!';
            }
        }
        if (len == 18) {
            re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
            var arrSplit = num.match(re);
            //检查生日日期是否正确 
            var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
                msg = '输入的身份证号里出生日期不对!';
            }
            else {
                //检验18位身份证的校验码是否正确。 
                var valnum;
                var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                var nTemp = 0, i;
                for (i = 0; i < 17; i++) {
                    nTemp += num.substr(i, 1) * arrInt[i];
                }
                valnum = arrCh[nTemp % 11];
                if (valnum != num.substr(17, 1)) {
                    msg = '18位身份证的校验码不正确,请核对!'; //应该为:' + valnum;
                }
            }
        }
    }
    if (msg != "") {
        msg += "\r\n按[确定]修改,按[取消]清空";
        if (window.confirm(msg)) {
            obj.focus();
        }
        else {
            obj.value = "";
        }
        //  alert(msg);
        //  obj.focus();
        return false;
    }
    return true;
}

function GetNumById(id) {
    var val = document.getElementById(id).value;
    if (val == "") {
        return 0;
    }
    else {
        return parseFloat(val);
    }
}

//判断查询字符串是否合法 onblur="CheckQueryStr(this)"
function CheckQueryStr(oField) {
    re = /select|update|delete|exec|count|'|、|‘|"|“|”|=|;|>|<|%/i;
    $sMsg = "请不要输入非法字符!"
    if (re.test(oField.value)) {
        alert($sMsg);
        oField.value = '';
        oField.focus();
        return false;
    }
}

//判断查询年度的字符串是否合法
function CheckYearStr(oField) {
    re = /^[1-9]\d{3}$/;
    $sMsg = "输入的年份格式有误!"
    var oFieldVal = $.trim(oField.value);
    if (oFieldVal != "" && !re.test(oFieldVal)) {
        alert($sMsg);
        oField.value = '';
        oField.focus();
        return false;
    }

}
//判断输入工程iD的字符串是否合法
function CheckNumStr(oField) {
    re = /^[0-9]+(.[0-9]{1,2})?$/;
    $sMsg = "请输入数字字符!"
    var oFieldVal = $.trim(oField.value);
    if (oFieldVal != "" && !re.test(oFieldVal)) {
        alert($sMsg);
        oField.value = '';
        oField.focus();
        return false;
    }

}
//屏蔽按键事件
function onlyInputNum2(event) {
    var keyCode = window.event ? event.keyCode : event.which;
    if (keyCode == 13 || keyCode == 8) {
        event.returnValue = false;
    } else {
        event.returnValue = true;
    }
}
//防止键盘按键引起的异常操作
function txtonkeydown(event) {
    var keyCode = window.event ? event.keyCode : event.which;
    if (keyCode == 13) {//enter键
        //                    alert("1");
        return false;
    }

}
//判断查询总产值的字符串是否合法
function CheckOutValueStr(oField) {
    var pattern_Money = /^(([1-9]\d*)(\.\d\d*)?)$|(0\.0?([1-9]\d*?))$/;
    var pattern_Zero = /^(([1-9]\d*)|0)(\.\d{1,*})?$/;
    $sMsg = "建筑业总产值(千元)格式有误!"
    var oFieldVal = $.trim(oField.value);
    if ($.trim(oFieldVal) != "" && (!pattern_Money.test($.trim(oFieldVal))) && (!pattern_Zero.test($.trim(oFieldVal)))) {
        alert($sMsg);
        oField.value = '';
        oField.focus();
        return false;
    }
}


//显示附件图片
function ShowAttachList(path) {
    var tpath = "../../Common/ImageShowList.aspx?FlowSN=";
    if (path == null) {
        path = tpath;
    }
    var FlowSn = document.getElementById("FlowSN").value;
    OpenModelWindow(path + FlowSn.toString(), 600, 500);
}

//将页面值复制到多行输入控件中
function CopyToListValue(col, ctlId) {
    //myText-none-0- -UCListEdit1
    if (ctlId == null || ctlId == "") {
        ctlId = "UCListEdit1";
    }
    var txt = document.getElementById("myText-none-0-" + col + "-" + ctlId);
    //txt.disabled = true;
    txt.value = event.srcElement.value;
}

//根据参数IsMax来决是否打开全屏窗口:IsMax为true打开全屏
function OpenNewWindow(strUrl, IsMax, widthPx, lengthPx, FormName) {

    /*
    if(strUrl.indexOf('/FlowCtrl/index.aspx')!=-1)
    {
    if(GetCookie("PageCount")>=1)
    {
    alert("其它事务正在处理,请先关闭其它事务!");
    return false;
    }
    }*/

    if (typeof (widthPx) == "undefined") {
        var widthPx = 700;
    }

    if (typeof (lengthPx) == "undefined") {
        var lengthPx = 400;
    }
    if (typeof (FormName) == "undefined") {
        var strFormName = "secretary";
    }
    else {
        var strFormName = FormName;
    }

    if (strUrl.indexOf('/FlowCtrl/index.aspx') != -1)
        var strFeatures = "width=" + widthPx + ",height=" + lengthPx + ",scrollbars=1,status=1,center=1,resizable=0";
    else
        var strFeatures = "width=" + widthPx + ",height=" + lengthPx + ",scrollbars=1,status=1,center=1,resizable=1";

    newwin = window.open("", "", strFeatures);  //strFormName

    if (IsMax) {
        if (document.all) {
            newwin.moveTo(0, 0)
            newwin.resizeTo(screen.width, screen.height)
        }
    }
    var intSite = strUrl.lastIndexOf("/")
    newwin.location = strUrl

}

//
function Year() {
    var i = 0;
    var nz = 0;
    var nk = 0;
    var ns = 0;
    while (true) {
        if (document.getElementById("myText-none-" + i + "-1-UCListEdit1") != null) {
            document.getElementById("myText-none-" + i + "-12-UCListEdit1").value = "";
            var a = 0;
            for (var j = 2; j < 12; j++) {
                if (document.getElementById("myText-none-" + i + "-" + j + "-UCListEdit1").value != "") {
                    a = new Number(document.getElementById("myText-none-" + i + "-12-UCListEdit1").value)
                    var b = new Number(document.getElementById("myText-none-" + i + "-" + j + "-UCListEdit1").value);
                    if (j < 8) {
                        a += b;
                    }
                    else {
                        a -= b;
                    }
                    document.getElementById("myText-none-" + i + "-12-UCListEdit1").value = a;
                    document.getElementById("myText-none-" + i + "-12-UCListEdit1").setAttribute("defaultValue", a);

                }
            }
            document.getElementById("myText-none-" + i + "-12-UCListEdit1").value = a;
            document.getElementById("myText-none-" + i + "-12-UCListEdit1").setAttribute("defaultValue", a);
            for (var x = 2; x < 8; x++) {
                if (document.getElementById("myText-none-" + i + "-" + x + "-UCListEdit1").value != "") {
                    nz = nz + new Number(document.getElementById("myText-none-" + i + "-" + x + "-UCListEdit1").value);
                }
            }
            for (var x1 = 8; x1 < 12; x1++) {
                if (document.getElementById("myText-none-" + i + "-" + x1 + "-UCListEdit1").value != "") {
                    nk = nk + new Number(document.getElementById("myText-none-" + i + "-" + x1 + "-UCListEdit1").value);
                }
            }
            ns = ns + new Number(document.getElementById("myText-none-" + i + "-12-UCListEdit1").value);
            //document.getElementById("nzsr").value = new Number(document.getElementById("nzsr").value)+ nz;

            i++;
        }
        else {

            break;
        }
    }
    document.getElementById("nzsr").value = nz;
    document.getElementById("nzsr").setAttribute("defaultValue", nz);

    document.getElementById("nzkc").value = nk;
    document.getElementById("nzkc").setAttribute("defaultValue", nk);

    document.getElementById("nsr").value = ns;
    document.getElementById("nsr").setAttribute("defaultValue", ns);
}

//
function AddRequireStyle() {
    try {
        var ids = WorkFlowFun.GetAllSaveRequires(parent.document.getElementById("FlowID").value, parent.document.getElementById("StepID").value, parent.document.getElementById("FormID").value, "0");
        if (ids.value.length > 0) {
            var items = ids.value.split("|");
            for (var item in items) {
                var obj = document.getElementById(items[item]);
                if (obj != null) {
                    obj.className = obj.className + " required *";
                    obj.style.cssText += "BORDER-BOTTOM-COLOR: red; BORDER-RIGHT-WIDTH: thin; BORDER-TOP-COLOR: red; BORDER-TOP-WIDTH: thin; BORDER-BOTTOM-WIDTH: thin; BORDER-RIGHT-COLOR: red; BORDER-LEFT-COLOR: red; BORDER-LEFT-WIDTH: thin;text-align:left;";
                }
            }
        }

        var idstr = WorkFlowFun.GetAllSaveExtensionattr(parent.document.getElementById("FlowID").value, parent.document.getElementById("StepID").value, parent.document.getElementById("FormID").value, "0");
        if (idstr.value.length > 0) {
            var iditems = idstr.value.split("|");
            for (var i = 0; i < iditems.length; i++) {
                var str = iditems[i].split(",");
                if (document.getElementById(str[0]) != null) {
                    if (document.getElementById(str[0]).value == '') {
                        document.getElementById(str[0]).value = str[1];
                        document.getElementById(str[0]).setAttribute("defaultValue", str[1]);
                    }
                }
            }
        }
    }
    catch (e) {

    }
}
//编辑权限控制,属性带有 nocontrol="true" 时,不给予控制
function AuthControl() {
    //debugger;
    var objs = document.getElementsByTagName("input");
    Controls(objs);
//    var objs2 = document.getElementsByTagName("select");
//    Controls(objs2);
//    var objs3 = document.getElementsByTagName("textarea");
//    Controls(objs3);

}
function Controls(objs) {
    if (document.getElementById("AuthorityControl").value == "False") {
        for (var i = 0; i < objs.length; i++) {
            if (objs[i].attributes["control"] != undefined && objs[i].attributes("control").value == "true") {
                objs[i].disabled = true;
            } else {

            }
        }
    }
}
function AutoResizeImage(maxWidth, maxHeight, objImg) {

    var img = new Image();
    img.src = objImg.src;
    var hRatio;
    var wRatio;
    var Ratio = 1;
    var w = img.width;
    var h = img.height;
    wRatio = maxWidth / w;
    hRatio = maxHeight / h;
    if (maxWidth == 0 && maxHeight == 0) {
        Ratio = 1;
    } else if (maxWidth == 0) {//
        if (hRatio < 1) Ratio = hRatio;
    } else if (maxHeight == 0) {
        if (wRatio < 1) Ratio = wRatio;
    } else if (wRatio < 1 || hRatio < 1) {
        Ratio = (wRatio <= hRatio ? wRatio : hRatio);
    }
    if (Ratio < 1) {
        w = w * Ratio;
        h = h * Ratio;
    }
    objImg.height = h;
    objImg.width = w;

    return objImg;
}

你可能感兴趣的:(javascript随笔)