JavaScript验证用户输入

编辑改随笔

JavaScript用户输入验证

/*

       名字:Common.js

       功能:通用JavaScript脚本函数库






       包括:






                     1.Trim(str)--去除字符串两边的空格
                     
                     2.LTrim(str)--去除字符串左边的空格
                     
                     3.RTrim(str)--去除字符右边的空格      

                     4.IsEmpty(obj)--验证输入框是否为空






                     5.IsNum(obj)--验证是否为数字






                     6.IsFloat(objStr,sign,zero)--验证是否为浮点数

                     7.IsEnLetter(objStr,size)--验证是否为26个字母
                     8.getPostfixText(str)--字符串加后缀"_全局"
                     9.delPostfixText(str)--字符串去后缀"_全局"





                     
                     以及其它的一些验证类函数

*/
 

/*

==================================================================

LTrim(string):去除左边的空格






==================================================================

*/
    
function LTrim(str)

{

    var whitespace = new String(" \t\n\r");

    var s = new String(str);

    

    if (whitespace.indexOf(s.charAt(0)) != -1)

    {

        var j=0;
        var i = s.length;

        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)

        {

            j++;

        }

        s = s.substring(j, i);

    }

    return s;

}

 

/*

==================================================================

RTrim(string):去除右边的空格






==================================================================

*/

function RTrim(str)

{

    var whitespace = new String(" \t\n\r");

    var s = new String(str);

 

    if (whitespace.indexOf(s.charAt(s.length-1)) != -1)

    {

        var i = s.length - 1;

        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)

        {

            i--;

        }

        s = s.substring(0, i+1);

    }

    return s;

}

function CTrim(str)
{
    var s = new String(str);
    if (s.length < 4)
    {
        return s;
    }
    for ( var i = 1; i < s.length-2;)
    {
        if (s.charAt(i) == ' ' && s.charAt(i+1) == ' ')
        {
            s = s.substring(0, i+1) + s.substring(i+2, s.length);
            continue;
        }
        i ++;
    }
    return s;
}

/*

==================================================================

Trim(string):去除前后空格

==================================================================

*/

function Trim(str)

{
    return CTrim(RTrim(LTrim(str)));
}
    

/*

================================================================================

验证类函数






================================================================================

*/ 

function IsEmpty(obj)

{

    obj=document.getElementsByName(obj).item(0);

    if(Trim(obj.value)=="")

    {    

        if(obj.disabled==false && obj.readOnly==false)

        {

            obj.focus();

        }
        return true;    
    }
    return false;
}

//数字判断函数
function IsNum(obj) 
{    
    obj=document.getElementsByName(obj).item(0);
    obj.value=Trim(obj.value);
    if(obj.value == "")
    {
        return false;
    }
    var regex=/[^0-9]/;
    if(obj.value.match(regex)){//match(/[^0-9]/)){
        obj.focus();
        return false;
    }
    return true;
}

/*
** IP 检测函数





**
*/

function CheckIpByMask(nIp, nMask)
{
    if (((nIp|nMask)== -1) || (((nIp|nMask)+Math.pow(2,32)) == nMask))
    {
        return false;
    }
    
    return true;
}

//允许ip值为0
function ChkIP2(ip1,ip2,ip3,ip4)
{
    if(IsNum(ip1)==false||IsNum(ip2)==false||IsNum(ip3)==false||IsNum(ip4)==false)
        return false;
    if(IsEmpty(ip1)||IsEmpty(ip2)||IsEmpty(ip3)|IsEmpty(ip4))
        return false;
    vip1=document.getElementsByName(ip1).item(0);
    vip2=document.getElementsByName(ip2).item(0);
    vip3=document.getElementsByName(ip3).item(0);
    vip4=document.getElementsByName(ip4).item(0);
    if(parseInt(vip1.value)<0||parseInt(vip1.value)>255||parseInt(vip2.value)<0||parseInt(vip2.value)>255
     ||parseInt(vip3.value)<0||parseInt(vip3.value)>255||parseInt(vip4.value)<0||parseInt(vip4.value)>255)
    {
        return false;
    }
    return true;
}

//不允许ip值为0
function ChkIP(ip1,ip2,ip3,ip4)
{
    if(IsNum(ip1)==false||IsNum(ip2)==false||IsNum(ip3)==false||IsNum(ip4)==false)
        return false;
    if(IsEmpty(ip1)||IsEmpty(ip2)||IsEmpty(ip3)|IsEmpty(ip4))
        return false;
    vip1=document.getElementsByName(ip1).item(0);
    vip2=document.getElementsByName(ip2).item(0);
    vip3=document.getElementsByName(ip3).item(0);
    vip4=document.getElementsByName(ip4).item(0);
    var nip1=parseInt(vip1.value);
    var nip2=parseInt(vip2.value);
    var nip3=parseInt(vip3.value);
    var nip4=parseInt(vip4.value);
    if(nip1<0||nip1>255||nip2<0||nip2>255
       ||nip3<0||nip3>255||nip4<0||nip4>255
       ||nip1==0&&ip2==0&&ip3==0&&ip4==0)
    {
        return false;
    }
    //将页面上对应输入框替换成parseint后的结果
    vip1.value = nip1;
    vip2.value = nip2;
    vip3.value = nip3;
    vip4.value = nip4;
    
    return true;
}

function ChkMask(ip1,ip2,ip3,ip4)
{
    if(ChkIP(ip1,ip2,ip3,ip4)==false)return false;
    var mask1=parseInt(document.getElementsByName(ip1).item(0).value);
    var mask2=parseInt(document.getElementsByName(ip2).item(0).value);
    var mask3=parseInt(document.getElementsByName(ip3).item(0).value);
    var mask4=parseInt(document.getElementsByName(ip4).item(0).value);
    var tmp = (mask1*Math.pow(2,24)) + (mask2*Math.pow(2,16)) + (mask3*Math.pow(2,8)) + mask4;
    if(tmp < Math.pow(2,31))
    {
        return false;
    }
    else
    {
        tmp -=  Math.pow(2,31);
        //后续位必须为连续的1
        for (i = 30; i > 1; i --)
        {
            if (tmp == 0)
            {
                break;
            }
            else if(tmp < Math.pow(2,i))
            {
                return false;
            }
            else
            {
                tmp -= Math.pow(2,i);
            }
        }
    }
    return true;
}

/*
 ---------------------------------------------------------------------------------------------
 更严格的IP检测函数:可检测各种非法IP
 名  称:MyCheckIP(ip1,ip2,ip3,ip4),





 参``数:ip1,ip2,ip3,ip4均为ip框对应的name
 返回值:true-有效IP;false-无效IP;
 ---------------------------------------------------------------------------------------------
*/
function MyCheckIP(ip1,ip2,ip3,ip4)
{
    var obj1 = document.getElementsByName(ip1).item(0);
    var obj2 = document.getElementsByName(ip2).item(0);
    var obj3 = document.getElementsByName(ip3).item(0);
    var obj4 = document.getElementsByName(ip4).item(0);
    var nIP1 = StrToInt(obj1.value);
    var nIP2 = StrToInt(obj2.value);
    var nIP3 = StrToInt(obj3.value);
    var nIP4 = StrToInt(obj4.value);
    //是否为非法字符





    if(isNaN(nIP1) || isNaN(nIP2) || isNaN(nIP3) || isNaN(nIP4))
    {
            return false;
    }
    //首位必需为1-223之间除127之外的任一数字
    if(nIP1<1 || nIP1 > 223 || nIP1 == 127 )
    {
            return false;
    }
    if( nIP2<0 || nIP2>255 || nIP3<0 || nIP3>255 )
    {
        return false;    
    } 
    //末位不能为0或255
    if(nIP4<1 || nIP4>254)
    {
        return false;    
    }
    obj1.value = nIP1;
    obj2.value = nIP2;
    obj3.value = nIP3;
    obj4.value = nIP4;
    
    return true;
}

/*
 ---------------------------------------------------------------------------------------------
 更严格的子网检测函数:可检测各种非法子网IP
 名  称:MyCheckNet(ip1,ip2,ip3,ip4),





 参``数:ip1,ip2,ip3,ip4均为ip框对应的name
 返回值:true-有效IP;false-无效IP;
 ---------------------------------------------------------------------------------------------
*/
function MyCheckNet(ip1,ip2,ip3,ip4)
{
    var obj1 = document.getElementsByName(ip1).item(0);
    var obj2 = document.getElementsByName(ip2).item(0);
    var obj3 = document.getElementsByName(ip3).item(0);
    var obj4 = document.getElementsByName(ip4).item(0);
    var nIP1 = StrToInt(obj1.value);
    var nIP2 = StrToInt(obj2.value);
    var nIP3 = StrToInt(obj3.value);
    var nIP4 = StrToInt(obj4.value);
    //是否为非法字符





    if(isNaN(nIP1) || isNaN(nIP2) || isNaN(nIP3) || isNaN(nIP4))
    {
            return false;
    }
    //首位必需为1-223之间除127之外的任一数字
    if(nIP1<1 || nIP1 > 223 || nIP1 == 127 )
    {
            return false;
    }
    if( nIP2<0 || nIP2>255 || nIP3<0 || nIP3>255 || nIP4<0 || nIP4>255)
    {
        return false;    
    } 

    obj1.value = nIP1;
    obj2.value = nIP2;
    obj3.value = nIP3;
    obj4.value = nIP4;
    
    return true;
}


/*

IsInt(string,string,int or string):(测试字符串,+ or - or empty,empty or 0)

功能:判断是否为整数、正整数、负整数、正整数+0、负整数+0

*/

function IsInt(objStr,sign,zero)

{

    var reg;    

    var bolzero;    

    if(Trim(objStr)=="")

    {

        return false;

    }

    else

    {

        objStr=objStr.toString();

    }    

    

    if((sign==null)||(Trim(sign)==""))

    {

        sign="+-";

    }

    if((zero==null)||(Trim(zero)==""))

    {

        bolzero=false;

    }

    else

    {

        zero=zero.toString();

        if(zero=="0")

        {

            bolzero=true;

        }

        else

        {

            alert("检查是否包含0参数, 只可为(空、0)");

        }

    }


    switch(sign)

    {

        case "+-":

            //整数

            reg=/(^-?|^\+?)\d+$/;            

            break;

        case "+": 

            if(!bolzero)           

            {

                //正整数






                reg=/^\+?[0-9]*[1-9][0-9]*$/;

            }

            else

            {

                //正整数+0

                //reg=/^\+?\d+$/;

                reg=/^\+?[0-9]*[0-9][0-9]*$/;

            }

            break;

        case "-":

            if(!bolzero)

            {

                //负整数






                reg=/^-[0-9]*[1-9][0-9]*$/;

            }

            else

            {

                //负整数+0

                //reg=/^-\d+$/;

                reg=/^-[0-9]*[0-9][0-9]*$/;

            }            

            break;

        default:

            alert("检查符号参数, 只可为(空、+、-)");

            return false;

            break;

    }
    

    var r=objStr.match(reg);

    if(r==null)

    {

        return false;

    }

    else

    {        

        return true;     

    }

}

 

/*

IsFloat(string,string,int or string):(测试字符串,+ or - or empty,empty or 0)

功能:判断是否为浮点数、正浮点数、负浮点数、正浮点数+0、负浮点数+0

*/

function IsFloat(objStr,sign,zero)

{

    var reg;    

    var bolzero;    

    if(Trim(objStr)=="")

    {

        return false;

    }

    else

    {

        objStr=objStr.toString();

    }    

    

    if((sign==null)||(Trim(sign)==""))

    {

        sign="+-";

    }

    

    if((zero==null)||(Trim(zero)==""))

    {

        bolzero=false;

    }

    else

    {

        zero=zero.toString();

        if(zero=="0")

        {

            bolzero=true;

        }

        else

        {

            alert("检查是否包含0参数, 只可为(空、0)");

        }

    }

    

    switch(sign)

    {

        case "+-":

            //浮点数






            reg=/^((-?|\+?)\d+)(\.\d+)?$/;

            break;

        case "+": 

            if(!bolzero)           

            {

                //正浮点数

                reg=/^\+?(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;

            }

            else

            {

                //正浮点数+0

                reg=/^\+?\d+(\.\d+)?$/;

            }

            break;

        case "-":

            if(!bolzero)

            {

                //负浮点数

                reg=/^-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;

            }

            else

            {

                //负浮点数+0

                reg=/^((-\d+(\.\d+)?)|(0+(\.0+)?))$/;

            }            

            break;

        default:

            alert("检查符号参数, 只可为(空、+、-)");

            return false;

            break;

    }

    

    var r=objStr.match(reg);

    if(r==null)

    {

        return false;

    }

    else

    {        

        return true;     

    }

}

//将ip由*.*.*.*格式转为long型





function IPStrToLong(str)
{
    var ip=0;
    var array=str.split(".");
    if(array.length == 4)
    {
        ip=parseInt(ip)+parseInt(array[0])*16777216;
        ip=parseInt(ip)+parseInt(array[1])*65536;
        ip=parseInt(ip)+parseInt(array[2])*256;
        ip=parseInt(ip)+parseInt(array[3]);
    }
    
    return parseInt(ip);
}

//将字符串转为整数,对8进制和16进制不作转换
function StrToInt(str)
{
    var result="";
    var index=0;
    var flag=0;
    while(index<str.length){
        if(parseInt(str.charAt(index))==0&&flag==0)flag=1;
        if(parseInt(str.charAt(index))>0&&parseInt(str.charAt(index))<=9)
        {
            break;
        }        
        index++;
    }
    //前一个字符是否为正,负号
    if(index>0&&(str.charAt(index-1)=="-"||str.charAt(index-1)=="+"))
    {
        result+=str.charAt(index-1);
    }
    while(index<str.length)
    {
        if(parseInt(str.charAt(index))>=0&&parseInt(str.charAt(index))<=9)
        {
            result+=str.charAt(index);
        }
        else break;
        index++;
    }
    if(result==""&&flag==1)
    {
        result="0";
    }
    return parseInt(result);
}

/*1.显示/隐藏 helptable */

function onHelp()
{
    var table=document.getElementById("helptable");
    if(table.rows[1].style.display=="none")
    {
        table.rows[1].style.display="";
    }
    else
    {
        table.rows[1].style.display="none";
    }
}
/*初始化时的错误信息检测*/

function error_init()
{
    var table=document.getElementById("ErrorTable");
    if(document.getElementById("error").value!="")
    {
        alert("保存配置信息出错,详情请查看错误信息");
        table.rows[0].style.display="";
    }
    if (document.getElementById("error2").value != "")
    {
        alert(document.getElementById("error2").value);
    }
}
/*点击“查看错误信息时”用于显示错误信息*/

function onShowError()
{
    var error=document.getElementById("error");
    var winObj=window.open();
    if(winObj == null)
    {
        alert("由于您的浏览器禁止了弹出窗口,部分信息无法显示!");
        return;
    }
    var content="<html><head><meta http-equiv=Content-Type content=text/html; charset=utf-8><title>错误信息</title>";
    content+="<link href=/html/STYLE.CSS rel=stylesheet type=text/css></head>";
    content+="<body class='body3'><form><table><tr><td class=errorinfo>";    
    content+=error.value;
    content+="</td></tr></table></form></body></html>";
    winObj.document.open();
    winObj.document.write(content);    
    winObj.document.close();
}

/*****************************************************************
    EnterCancel()            功能:屏蔽键盘输入的回车键
*****************************************************************    */
function EnterCancel()
{
    if(event.keyCode == 13)
    {
        event.cancelBubble = true;
    }
}    

/************************************************************************
    ChangeToTab() 功能:在ip输入框中输入"."转向下一个对象





*************************************************************************/
function ChangeToTab()
{
    if(event.keyCode == 110 || event.keyCode == 190)
    {
        event.keyCode = 9;//tab    
    }
    return false;
}

/*********************************************************************************
                设置cookie,删除指定cookie,获取cookie值





1.GetCookieVal(offset)  得到第offset个cookie值对,
2.GetCookie(name)        根据cookie name得到cookie值





3.SetCookie(name,value,expires,path,domain,secure)    创建或修改cookie
4.DelCookie(name,path,domain)        删除cookie    
**********************************************************************************/
//得到第offset个cookie值对,
function GetCookieValue(offset)
{
    var end = document.cookie.indexOf(";", offset);
    if(end == -1)
    {
            end = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, end));
}

//根据cookie name得到cookie值





function GetCookie(name)
{
    var arg = name + "=";    
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while( i < clen)
    {
            var  j = i + alen 
            if(document.cookie.substring(i,j) == arg)
            {
                return GetCookieValue(j);
            }
            i = document.cookie.indexOf(" ",i) + 1;
            if( i == 0)
            {
                    break;
            }
    }
    return "";
}


//创建或修改cookie
function SetCookie(name,value,expires,path,domain,secure)
{
    document.cookie = name + "=" +    escape(value) + 
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") + 
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


//删除cookie
function DelCookie( name ,path, domain)
{
        if(GetCookie(name) != "")
        {
            document.cookie = name + "=" +
                ((path) ? "; path="+path : "") +
                ((domain) ? "; domain="+domain : "") + 
                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
            
            return true;
        }
        
        return false;
}
/*******************************
//在父页面加上遮罩层,避免谷歌下
//可以重复弹出窗口引起一些问题
******************************/
function showMaskLayer()
{
    if(!isChrome())
    {
        return null;
    }
    var div=this.document.createElement("div");
    //div.style.width=parent.document.documentElement.scrollWidth - 20 +"px";
    div.style.width = "100%";
    //div.style.height=screen.height - 20 +"px";
    div.style.height = "100%";
    div.style.backgroundColor="#777";
    div.style.position="fixed";
    div.style.left=0;
    div.style.top=0;
    div.style.zIndex=9999;
    div.style.opacity = 0.2;

            
    this.document.body.appendChild(div);
    return div;
}

/*******************************
//去掉遮罩层
******************************/
function removeMaskLayer()
{
    var div = this;
    if(div != null)
    {
        this.parentNode.removeChild(div);
    }
}

/*********************************
//在Firefox下调整弹出位置
*********************************/
function AdjustPostion(szParm)
{
    if(!isFirefox() && window.showModalDialog) //其他浏览器下已经是在中间弹出
    {
        return szParm;
    }
    var pureNum = new RegExp(/^[0-9]{1,}$/);
    var winHeight = szParm.replace(/.*dialogHeight:([0-9]*)px.*/,"$1");
    var winWidth = szParm.replace(/.*dialogWidth:([0-9]*)px.*/,"$1");
    var leftPos = screen.width;
    var topPos = screen.height;
    var defSize = 600; //没有设置高度时,有一个默认值
    
    if(!pureNum.test(winHeight))
    {
        if(defSize >= topPos)
        {
            topPos = 0; //没有设置值,屏幕分辩率又很小时,直接在左上角显示,一般不会出现
        }
        else
        {
            topPos = (topPos - 600)/2;    
        }
        
    }
    else 
    {
        topPos = (topPos - parseInt(winHeight) - 60)/2; //需要考虑标题栏的高度
    }
    
    if(!pureNum.test(winWidth))
    {
        if(defSize >= leftPos)
        {
            leftPos = 0;
        }
        else
        {
            leftPos = (leftPos - 600)/2;    
        }        
    }
    else
    {
        leftPos = (leftPos - parseInt(winWidth))/2;
    }    
    return szParm + ";dialogTop:" + topPos + "px" + ";dialogLeft:" + leftPos + "px";
}
/*******************************************
将Showmodaldialog的参数转换为window.open的形式
*******************************************/
function ParamChange(arg)
{
    var str = "";
    var szTmp = "";
    var args = arg.split(";");
    var len = args.length;
    for (var i = 0; i < len; i++)
    {
        an = args[i].split(/=|:/)[0];
        av = args[i].split(/=|:/)[1];
        switch(an)
        {
            case "dialogWidth":
                szTmp = "width=" + av + ",";
                str += szTmp;
                 break;
            case "dialogHeight":
                szTmp = "height=" + av + ",";
                str += szTmp;
                break;
            case "scroll":
                if (av == "0" || av == "no" || av == "off"){
                    str += "scrollbars=no,"; 
                } else{
                    str += "scrollbars=yes,";
                }
                break;
            case "status":
                if (av == "0" || av == "no"){
                    str += "status=no,"; 
                } else{
                    str += "scrollbars=yes,";
                }                
                break;
            case "dialogTop":
                szTmp = "screenY=" + av + ",";
                str += szTmp;
                break;
            case "dialogLeft":
                szTmp = "screenX=" + av + ",";
                str += szTmp;
                break;
            case "":
                break;
            default:
                szTmp = an + "=" + av + ",";
                str += szTmp;
                break;
        }
    }
    return str;
}
/********************
关闭子页面后的处理
********************/
function AfterClose()
{    

    //关闭窗口
    if (g_openwnd == null || g_openwnd.closed)
    {
        try{
        if (g_div_main)
        {
            removeMaskLayer.apply(g_div_main, arguments);
        }
        if (g_div_left)
        {
            removeMaskLayer.apply(g_div_left, arguments);
        }
        if (g_closewnd_cb)
        {
            g_closewnd_cb();
        }
        }catch(e)
        {
        }
        g_openwnd = null;
        g_closewnd_cb = null;
        g_div_main = null;
        g_div_left = null;
        
        window.top.clearInterval(g_wnd_close_timer);
        g_wnd_close_timer_flag = false;
    }
}
/************************************************************************************
    MyshowModalDialog()
       用来替换showModalDialog(),因为当IE屏蔽弹出窗口时,子页面中执行showModalDialog()
    会出异常,因此要在其前后加入处理异常的try,catch,为了方便以后更改,固在统一改用
    另外一个函数来替换
*************************************************************************************/

function MyshowModalDialog(path, obj, string, cb)
{
    var rv = true;
    string += ";help:no;";//staus:no;";
    exp1 = new RegExp(/dialogWidth:[1-2][0-9][0-9]px/);
    exp2 = new RegExp(/dialogWidth:[3][0-5][0-9]px/); 
    if(exp1.test(string))
    {
        //string += ";dialogWidth:360px;"
        var szTmp = string.replace(/dialogWidth:[1-2][0-9][0-9]px/,"dialogWidth:360px");
        string = szTmp;
    }
    else if(exp2.test(string))
    {
        var szTmp = string.replace(/dialogWidth:[3][0-5][0-9]px/,"dialogWidth:360px");
        string = szTmp;        
    }
    g_div_main = showMaskLayer();
    g_div_left = null;
    if(typeof(parent.frames['leftFrame']) != "undefined")
    {
        g_div_left = showMaskLayer.apply(parent.frames['leftFrame'], arguments);
    }
    string = AdjustPostion(string);
    if (window.showModalDialog)
    {
        try
        {
            window.showModalDialog(path, obj, string);
            //showModalDialog(path, obj, string);
        }
        catch(e)
        {
            alert("无法正常弹出窗口,\n\n请检查您的浏览器选项中是否选择了阻止弹出窗口!");
            rv = false;
        }
        if (g_div_main != null)
        {
            removeMaskLayer.apply(g_div_main, arguments);
        }
        if(g_div_left != null)
        {
            removeMaskLayer.apply(g_div_left, arguments);
        }
        g_openwnd = null;
        g_closewnd_cb = null;
        g_div_main = null;
        g_div_left = null;
    }else {
        string = ParamChange(string);
        var newWnd = window.open(path,"",string); 
        if (newWnd == null){
            alert("无法正常弹出窗口,\n\n请检查您的浏览器选项中是否选择了阻止弹出窗口!");
            rv = false;
        } else{
            newWnd.window.dialogArguments = obj;

            g_openwnd = newWnd;
            g_closewnd_cb = cb;

            if (typeof(g_wnd_close_timer_flag) == "undefined" || g_wnd_close_timer_flag == false) {
                g_wnd_close_timer = window.top.setInterval(AfterClose, 500);
                g_wnd_close_timer_flag = true;
            }
        }
    }
    
    return rv;
}



/*************************************************************************************\
ajx异步请求 -open的参数为false,所以其实是同步,非异步
makeRequest(csUrl,NoticeCgiToSave)
url             --    要连接的服务器(当是get的时候,可以直接将参数附在url中)
callback     --    返回后的处理函数
param            --    当是POST的时候,可以通过它上传提交内容,当是GET时此参数应为null
methods        --    POST/GET/HEADER,默认为POST
encodeType  -- 是否要设置http头部的content-type字段,当使用FormData方法将整个表单
                --构造成数据提交时,不能设置这个字段
***************************************************************************************/

function makeRequest(url, callback, param, methods,encodeType)
{
    if(!methods)
    {
        methods = 'POST';    
    }
    if(!encodeType)
    {
        encodeType = false;    
    }
    http_request = false;

  if(window.XMLHttpRequest) 
  {
        http_request = new XMLHttpRequest();
        if(http_request.overrideMimeType) 
        {
            http_request.overrideMimeType('text/xml');
        }
  } 
  else if (window.ActiveXObject)
  {
        try 
        {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) 
        {
      try
        {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) 
        {}
        }
  }

  if(!http_request) 
  {
        alert("对不起,您的IE不支持AJAX 对象,\n\n操作无法进行!");
        return false;
  }

    try
    {
      http_request.onreadystatechange = callback;
      http_request.open(methods, url, false);
      if(methods.toLowerCase() == "get")
      {
            http_request.send(null);
        }
        else
        { 
            if(encodeType == false)  //在ajax中需要提交FormData构造的表单数据时,不能设置下面这个
            {
                http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            if(!isChrome())
            {
                http_request.setRequestHeader("content-length",param.length); 
            }
            http_request.send(param);
        }
    }
    catch(E)
    {
        ;
    }
    if (http_request.readyState == 4 && http_request.status != 200)
    {
        if (http_request.status == 0 || http_request.status == 12029) //新浏览器断网时这个值是0
        {
            alert("连接失败,可能是网络不通,请检查!");
        }
        else if (http_request.status == 12152)
        {
            alert("连接中断,不确定请求是否完成!");
        }
        else
        {
            alert("连接失败("+http_request.status+")");
        }        
    }
    return true;
}

/*************************************************************************************\
ajx异步请求 - open的参数为true
makeRequest(csUrl,NoticeCgiToSave)
url             --    要连接的服务器(当是get的时候,可以直接将参数附在url中)
callback     --    返回后的处理函数
param            --    当是POST的时候,可以通过它上传提交内容,当是GET时此参数应为null
methods        --    POST/GET/HEADER,默认为POST
encodeType  -- 是否要设置http头部的content-type字段,当使用FormData方法将整个表单
                --构造成数据提交时,不能设置这个字段
***************************************************************************************/
function makeRequest_asyn(url, callback, param, methods,encodeType)
{
    if(!methods)
    {
        methods = 'POST';    
    }
    if(!encodeType)
    {
        encodeType = false;    
    }
    http_request = false;

  if(window.XMLHttpRequest) 
  {
        http_request = new XMLHttpRequest();
        if(http_request.overrideMimeType) 
        {
            http_request.overrideMimeType('text/xml');
        }
  } 
  else if (window.ActiveXObject)
  {
        try 
        {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) 
        {
      try
        {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) 
        {}
        }
  }

  if(!http_request) 
  {
        alert("对不起,您的IE不支持AJAX 对象,\n\n操作无法进行!");
        return false;
  }

    try
    {
      http_request.onreadystatechange = callback;
      http_request.open(methods, url, true);
      if(methods.toLowerCase() == "get")
      {
            http_request.send(null);
        }
        else
        { 
            if(encodeType == false)  //在ajax中需要提交FormData构造的表单数据时,不能设置下面这个
            {
                http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            if(!isChrome()) //Chrome下,设置长度字段被认为是不安全的行为,虽然不影响功能,但会给出错误提示
            {
                http_request.setRequestHeader("content-length",param.length); 
            }
            http_request.send(param);
        }
    }
    catch(E)
    {
        ;
    }
    return true;
}

function UnablePage()
{
    //禁用所有input(不禁用button)
    var oTagsInput = document.getElementsByTagName("input");  
     var nLength = oTagsInput.length; 
    for (var i=0; i<nLength; i++)  
    {   
        if (oTagsInput[i].type != "button")
        {
            oTagsInput[i].disabled = true;
            oTagsInput[i].className = "input_readonly";
        }
    }
    
    //禁用所有select
    oTagsInput = document.getElementsByTagName("select");  
    nLength = oTagsInput.length; 
    for (var i=0; i<nLength; i++)  
    {   
        oTagsInput[i].disabled = true;
        oTagsInput[i].className = "input_readonly";
    }

    //禁用textarea
    oTagsInput = document.getElementsByTagName("textarea");  
    nLength = oTagsInput.length; 
    for (var i=0; i<nLength; i++)  
    {   
        oTagsInput[i].disabled = true;
        oTagsInput[i].className = "input_readonly";
    }
}

//IE5以下不支持encodeURIComponent和encodeURI, Added by Czy
if(typeof encodeURIComponent!='function')
{
        var encodeURIComponent=function(s)
        {
                var result=[];
                var len=s.length;
                for(var i=0;i<len;i++)
                {
                        var code = s.charCodeAt(i);
                        if (code == 33 
                            || (code >= 39 && code <= 42)
                            || code == 45
                            || code == 46
                            || (code >= 48 && code <= 57)
                            || (code >= 65 && code <= 90)
                            || code == 95
                            || (code >= 97 && code <= 122)
                            || code == 126)
                        {
                            result += s.charAt(i);
                        }
                        else
                        {
                            result += encodeUTF8(s.charCodeAt(i));
                        }
                }
                //return result.join("");
                return result; 
        }
}

if(typeof encodeURI!='function')
{
        var encodeURI=function(s)
        {
                var result=[];
                var len=s.length;
                for(var i=0; i<len; i++)
                {
                        var code = s.charCodeAt(i);
                        if (code == 33
                            || code == 35
                            || code == 36
                            || (code >= 38 && code <= 59)
                            || code == 61
                            || (code >= 63 && code <= 90)
                            || code == 95
                            || (code >= 97 && code <= 122)
                            || code == 126)
                        {
                                //result.push(s.charAt(i));
                                result += s.charAt(i);
                        }

                        else
                        {
                                //result.push(encodeUTF8(code));
                                result += encodeUTF8(code);
                        }
                }
                //return result.join("");
                return result;
        }
}

function encodeUTF8(code)
{
        if(code<=16) 
               return "%0"+code.toString(16);

        var iByte=0;
        var i=0;
        result="";

        while(code>0x7f)
        {
                iByte=code%0x40; 
                code=(code-iByte)/0x40;
                result="%"+(iByte|0x80).toString(16).toUpperCase()+result;
                i++;
        }

        prefix=[0x0,0xc0,0xe0,0xf0,0xf8,0xfc];
        if(i>prefix.length)
        {
                i=5;
        }
        result="%"+(code|prefix[i]).toString(16).toUpperCase()+result;
        return result;
}
// begin add by lbc . 2011-12-19. 添加合法Mac地址判断函数。
// 返回值:0、MAC地址合法。1、MAC地址格式不正确。2、MAC地址为组播地址。
function isMacAddr(str)
{
    var nLen = strlen(str);
    if (nLen != 17)
    {
        return 1;
    }
    
    var zeroNum = 0;
    var fNum = 0;
    
    for (var i=0;i<nLen;i++)
    {
        switch(str.charAt(i))
        {
            case '0':
                zeroNum++;
                break;
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            case 'a':
            case 'b':
            case 'c':
            case 'd':
            case 'e':
                break;
            case 'f':
                fNum++;
                break;
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
                break;
            case 'F':
                fNum++;
                break;
            case '-':
                if ( i != 2 && i != 5 && i != 8 && i != 11 && i != 14)
                {
                    return 1;
                }
                break;
            default:
                return 1;
        }
    }
    if(str.charAt(2) != '-' || str.charAt(5) != '-' || str.charAt(8) != '-' || str.charAt(11) != '-' || str.charAt(14) != '-')
    {
        return 1;
    }
    if (zeroNum == 12 || fNum == 12)
    {
        return 2;
    }
    
    /*modifi for TD 13540, 组播地址判断应以第48位为1来判断*/
    /*
    if(str.charAt(0) == '0' && str.charAt(1) == '1' && str.charAt(3) == '0' && str.charAt(4) == '0' && str.charAt(6) == '5' && (str.charAt(7) == 'e' || str.charAt(7) == 'E'))
    {
        return 2;
    }
    */
    var LastByte = 0;
    LastByte = parseInt(str.substr(0,2),16);
    if(LastByte % 2 == 1)
    {
        return 2;
    }
    
    return 0;
}
// end add

// begin add by lbc . 2011-11-19 . 将带“-” 的MAC地址转换为不带“-” 的MAC地址
function macLongFormatToShort(str)
{
    result = str.substr(0,2) + str.substr(3,2) + str.substr(6,2) + str.substr(9,2) + str.substr(12,2) + str.substr(15,2);
    return result;
}
// end add

// begin add by lbc . 2011-11-19. 将不带“-” 的MAC地址转换为带“-” 的MAC地址
function macShortFormatToLong(str)
{
    result = str.substr(0,2) + "-" + str.substr(2,2) + "-" + str.substr(4,2) + "-"
        + str.substr(6,2) + "-" + str.substr(8,2) + "-" + str.substr(10,2);
    return result;
}
// end add
(function(win)
{
    var ua = navigator.userAgent.toLowerCase(),
    DOC = document, 
    check = function(r)
    {
        return r.test(ua);
    }, isOpera = check(/opera/), 
     docMode = DOC.documentMode,    
    isIE = !isOpera && check(/msie/),
    isIE7 = isIE && (check(/msie 7/) || docMode == 7),
    isIE8 = isIE && (check(/msie 8/) && docMode != 7),
    isIE6 = isIE && !isIE7 && !isIE8;
    win.SF = win.SF||{};
    SF.isIE = isIE;
    SF.isIE6 = isIE6;
    SF.isIE7 = isIE7;
    SF.isIE8 = isIE8;
})(window);

String.format =function (b) {
         var a = Array.prototype.slice.call(arguments, 1); 
         return b.replace(/\{(\d+)\}/g, function (c, d) {return a[d];}); 
}

function Mask(msg)
{
        var el =  document.createElement("div"),isShow =false,
            docHeight = document.body.clientHeight,
            docWidth = document.body.clientWidth, 
            str = ["<div class=\"maskDivIE\" style=\" height: 100%;\">", 
                       " <div style=\"height:16px; padding:10px; border:1px solid #009933; width:300px;position:absolute; background-color:#FFFFFF; color:#003300\">",
                            "<img  style=\"float:left;\" src=\"/html/images/Dimg.gif\"/> ",
                            "<div class=\"txt\" style=\"padding-left:15px; float:left;font-size:13px;\">{0}</div>",
                          // "<a onclick=\"closeMask()\" style=\"cursor:pointer;\"></a>", 
                    " </div>",    
             "</div> "];
         
          el.className="ui-overlay";
          el.style.height=400;
          el.style.diaplay="none";
          document.body.appendChild(el);
          el.innerHTML=String.format(str.join(""),msg) ; 
          function center(){
              var disel = el.children[0].children[0];
              disel.style.top =docHeight/2-20;
              disel.style.left = docWidth/2 - 150;
          }
          function showMask()
          {
                el.style.display="";
              center();
              isShow = true;
          }
          function hideMask()
          {
                el.style.display="none";
              isShow = false;
          }
          function updateMaskText(txt)
          {
               el.innerHTML=String.format(str.join(""),txt) ;
          }
          return {
                show:showMask,
              hide:hideMask,
              el:el,
              update:updateMaskText 
          }
}

//add by wlb for mig4.0(合入MIG3.0)
function getPostfixText(str)
{
    str = Trim(str);
    if (str == "")
    {
        return str;
    }
    
    var postfix = "_全局";
    var pflen = postfix.length;
    var npos = str.length - pflen;
    if (npos > 0 && str.substring(npos) == postfix)
    {
        return str;
    }

    return str+postfix;
}

function delPostfixText(str)
{
    str = Trim(str);
    if (str == "")
    {
        return str;
    }
    
    var postfix = "_全局";
    var pflen = postfix.length;
    var npos = str.length - pflen;
    if (npos > 0 && str.substring(npos) == postfix)
    {
        return str.substring(0, npos);
    }

    return str;
}
//end add by wlb for mig4.0
//如果是MIG模板则添加_全局
//如果不是MIG模板则不允许设置_全局结束
function SetPostfixText(str, bPlatMig)
{
    var postfix = "_全局";
    var pflen = postfix.length;
    var npos = str.length - pflen;
    if (npos > 0 && str.substring(npos) == postfix)
    {
        return bPlatMig == "1" ? str : "";
    }
    return bPlatMig == "1" ? str+postfix : str;
}

//xiaoxiong添加 使页面可输入内容不可用
function DisablePage()
{
    var allInput = document.body.getElementsByTagName("input");
    for(var i = 0 ; i<allInput.length;i++)
    {
        var item = allInput[i];
        if(item.type=="text" || item.type=="radio" || item.type=="checkbox" || item.type=="password")
        {
            item.disabled=true;
        }
    }
    var allSelect = document.body.getElementsByTagName("select");
    for(var i = 0 ; i<allSelect.length;i++)
    {
        var item = allSelect[i];
        item.disabled=true;
    }
    var allTextarea = document.body.getElementsByTagName("textarea");
    for(var i = 0 ; i<allTextarea.length;i++)
    {
        var item = allTextarea[i];
        item.disabled=true;
    }
}
/* 初始化搜索框
 * id: 搜索框的id
 * searchfun: 搜索函数
 * buttonid: 搜索按钮的id
*/
function InitSearchInput(id, searchfun, buttonid)
{
    var obj = document.getElementById(id);
    if(obj.value == "")//初始化时并没有输入
    {
        obj.checked = false;
        obj.style.color = "gray"
        obj.value = obj.title;
    }
    else
    {
        obj.checked = true;
        obj.style.color = "black";
        //搜索后聚焦
        /*TD7767 如果对象已经被隐藏,调用focus会出错,去掉
        obj.focus();
        var count=obj.value.length;
        var a = obj.createTextRange();
        a.moveStart('character',count);
        a.collapse(true);
        a.select();
        */
    }
    //聚焦时
    obj.onfocus = function()
    {
        if(obj.checked == false)
        {
            this.value = "";
        }
        this.style.color="black";
    };
    //失去焦点时
    obj.onblur = function()
    {
        if(this.value == "")
        {
            this.style.color = "gray"
            this.value = this.title;
            this.checked = false;
        }
        else
        {
            this.style.color = "black";
            this.checked = true;
        }
    };
    //回车
    var onkeydownfun = "if(event.keyCode == 13)" + 
                     "{" +
                        "if(typeof " + searchfun + " == 'function')" + 
                        "{" + 
                            searchfun + "(this.value);" +
                        "}" + 
                        "try{this.focus();} catch(err){}return false;" +        //TD7767 这里不会出现被隐藏
                     "}";
    obj.onkeydown = new Function("", onkeydownfun);
    //点击搜索
    var searfuncmd = searchfun + " ((document.getElementById('" + id + "').checked == false) ? '' : document.getElementById('" + id + "').value);";
    var ifcmd = "if(typeof " + searchfun + " == 'function')";
    var strcmd = ifcmd + "{" + searfuncmd + "}" + "try{document.getElementById('" + id + "').focus()} catch(err){}return false;";//退出时获取焦点 //TD7767 这里不会出现被隐藏
    document.getElementById(buttonid).onclick = new Function("", strcmd);
}
/*
 * 发出ajax请求
 * bAsync 可选,是否异步,默认是异步的
 */
function ajaxRequest(url,postStr,responseFunc,srcObject, bAsync)
{
  var bAsyncReq = (typeof bAsync === "undefined") ? true : bAsync;
    
    
    if(!bAsyncReq)
    {
        makeRequest(url,null,postStr);
         var rc = responseFunc(http_request,srcObject);
        if(typeof rc === "undefined")
            return true; /* 无返回值直接返回true */
        else
            return rc;
    }
    else
    {
        makeRequest_asyn(url,function()
        {
            if (http_request.readyState == 4 && http_request.status == 200)
            {
                responseFunc(http_request,srcObject);
                return true;
            }
        },
        postStr);    
    }
    return true;
}

function respType(respStr)
{
    var typestr = respStr.substring(0,7);
    var infostr = "";

    if( respStr.indexOf("登录",0) >=0 )
        typestr = "invalid";
    if ( typestr!="success" && typestr!="errored" && typestr!="invalid" )    
    {
        typestr = "notrecg";
        if(strlen(respStr) > 150)
            infostr = "未知错误!";
        else
           infostr = respStr;
    }else{
        if ( typestr == "invalid")
            infostr = "请重新登录!"
        else
            infostr = respStr.substring(8);
    }

    return {type:typestr,info:infostr};
}
function isIE()
{
    return navigator.userAgent.indexOf('MSIE') >= 0 || navigator.userAgent.indexOf('Trident') >= 0;
}

function cancelBack()
{
    if(event.keyCode == 8)
    {
        
        event.cancelBubble = true;
        event.returnValue = false;
        return false;
    }
}

function initFileSpan(textId,fileId,fileName,onchangeEvent,displayStr)
{
    var filespan = document.getElementById("filespan");
    filespan.style.display="inline";
    filespan.innerHTML="<input type=text name="+textId+" class=input2 id="+textId+" readonly />\n" +
                        "<input type=button class=buttons id=filebutton value=\"浏览 ...\" id=filebutton />" +
                        "<input type=file id="+fileId+" name="+fileName+" />";
    var text = document.getElementById(textId);
    var button = document.getElementById("filebutton");
    var file = document.getElementById(fileId);
    
    text.style.backgroundColor = "#EEEEEE";
    if (displayStr != null)
    {
        text.value = displayStr;
        text.style.color = "#CDC5BF";
    }
    button.style.width = "73px";
    if(navigator.userAgent.indexOf('MSIE') >= 0)//IE7,8,9,10
    {
        button.style.position    =    "absolute";
        button.style.right    =    "0px";
    }
    else//IE11,ff,chrome
    {
        button.align = "right";
        button.style.margin = "0px";
    }
    
    file.style.width    =    "73px";
    file.style.height    =    "18px";
    file.style.position    =    "absolute";
    if(navigator.userAgent.indexOf('MSIE') >= 0)//IE7,8,9,10
    {
        file.style.top    =    "1px";
        button.style.top = "-1px";
        file.style.right    =    "1px";
        
    }
    else//IE11,ff,chrome
    {
        file.style.top    =    "-3px";
        file.style.right    =    "0px";
    }
    if(isIE10())
    {
        button.style.top = "-2px";
    }
    
    file.style.margin    =    "0px";
    file.style.padding    =    "0px";
    file.style.border    =    "none";
    file.style.filter    =    "alpha(opacity = 0)";
    file.style.opacity    =    "0";
    
    file.onmouseover = function(){
        button.className = "buttons_hover";
    }
    file.onmouseout = function(){
        button.className = "buttons";
    }
    if (typeof onchangeEvent != "undefined" && onchangeEvent !=null)
    {
        file.onchange = onchangeEvent;
    }
    else
    {
        file.onchange = function(){
            text.value = getFileName(file.value);
            text.style.color = ""; //用户选择文件之后,清除原来的提示文本颜色设置
        }
    }
    
}
/*****************************
//增加文件大小和格式的判断函数
******************************/
function getFileName(fullname)
{
    var pos1 = fullname.lastIndexOf('/');
    var pos2 = fullname.lastIndexOf('\\');
    var pos  = Math.max(pos1, pos2)
    if( pos<0 )
        return fullname;
    else
        return fullname.substring(pos+1);
}

function CheckFileExt(filename,expectExt)
{
    if(filename.indexOf(".")>0)
    { 
        var name = filename.split("."); 
        var ext = name[name.length-1].toLowerCase(); 
        if(ext == expectExt)
        {
            return true;
        }        
    }
    
    return false;    
}
//返回以KB为单位的文件大小
function CheckFileSize(obj)
{
    if(obj == null)
    {
        return -1;
    }

    if(window.ActiveXObject)
    {
        try 
           {
            var fullname = obj.value;        
            var fso,f,fname,fsize;
            fso=new ActiveXObject("Scripting.FileSystemObject");
            f=fso.GetFile(fullname);//文件的物理路径
            fsize=f.Size; //文件大小(bit)
            fsize=fsize/1024; //以KB为单位
            return fsize;
        }
           catch(e) 
        {
             return -2;//控件创建失败,需要修改IE浏览器的设置
        }
    }
    if(obj.files && obj.files.length > 0)
    {
        return obj.files[0].size/1024;
    }
    return -1;
}

/****************************************
//将整个表单数据序列化为字符串用于ajax提交
//注意---表单中有文件时不能使用
*****************************************/
//获取指定form中的所有的<input>对象    
function getElements(formId) {    
    var form = document.getElementById(formId);    
    var elements = form.elements;    

    return elements;    
}   
  
//获取单个input中的【name,value】数组  
function inputSelector(element) {    
  if (element.checked)    
     return [element.name, element.value];    
}    
      
function input(element) { 
    if (element.type)
    {    
        switch (element.type.toLowerCase()) {    
          case 'submit':    
          case 'hidden':    
          case 'password':    
          case 'text':    
            return [element.name, element.value];    
          case 'checkbox':    
          case 'radio':    
            return inputSelector(element);  
        }
    }
    if (element.tagName.toLowerCase() == "select"){
        return [element.name,element.options[element.selectedIndex].value];      
    }    
    return false;    
}    
  
//组合URL  

function serializeElement(element) {      
    var parameter = input(element);    
    
    if (parameter) {    
      var key = encodeURIComponent(parameter[0]);    
      if (key.length == 0) return;    
    
      if (parameter[1].constructor != Array)    
        parameter[1] = [parameter[1]];    
          
      var values = parameter[1];    
      var results = [];    
      for (var i=0; i<values.length; i++) {    
        results.push(key + '=' + encodeURIComponent(values[i]));    
      }    
      return results.join('&');    
    }    
 }    
  
//调用方法     
function serializeForm(formId) {    
    var elements = getElements(formId);    
    var queryComponents = new Array();    
    
    for (var i = 0; i < elements.length; i++) {    
      var queryComponent = serializeElement(elements[i]);    
      if (queryComponent)    
        queryComponents.push(queryComponent);    
    }    
    
    return queryComponents.join('&');  
}

 

posted @ 2020-03-19 16:28  丫丫625202  阅读(661)  评论(0编辑  收藏  举报