`

utils.js

    博客分类:
  • JS
阅读更多
/**
 * common methods
 */
function trim(str) {
    return str.replace(/\s+$|^\s+/g, "");
}

function isValidLength(str, min, max) {
    if (isBlank(str) == 0) {
        return 1;
    }

    if (str.length >= min && str.length <= max) {
        return 0;
    } else if (str.length > max) {
        return 2;
    } else if (str.length < min) {
        return 3;
    }
}

function isBlank(str) {
    for (var i = 0; i < str.length; i++) {
        var c = str.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) {
            return 1;
        }
    }
    return 0;
}

function isIP(strIP) {
    if (isNull(strIP)) return false;
    var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g
    if (re.test(strIP))
    {
        if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) return true;
    }
    return false;
}

function isNull(str) {
    if (str == "") return true;
    var regu = "^[ ]+$";
    var re = new RegExp(regu);
    return re.test(str);
}

function isInteger(str) {
    var regu = /^[-]{0,1}[0-9]{1,}$/;
    return regu.test(str);
}

function checkMobile(s) {
    var regu = /^[1][3][0-9]{9}$/;
    var re = new RegExp(regu);
    return re.test(s);
}

function isNumber(s) {
    var regu = "^[0-9]+$";
    var re = new RegExp(regu);
    
    return s.search(re) != -1;
}

function isDecimal(str) {
    if (isInteger(str)) return true;
    var re = /^[-]{0,1}(\d+)[\.]+(\d+)$/;
    if (re.test(str)) {
        return !(RegExp.$1 == 0 && RegExp.$2 == 0);
    } else {
        return false;
    }
}

function isPort(str) {
    return (isNumber(str) && str < 65536);
}

function isEmail(str) {
    var myReg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;
    return myReg.test(str);

}

function isMoney(s) {
    var regu = "^[0-9]+[\.][0-9]{0,3}$";
    var re = new RegExp(regu);
    return re.test(s);
}

function isNumberOr_Letter(s) {
    var regu = "^[0-9a-zA-Z\_]+$";
    var re = new RegExp(regu);
    return re.test(s);
}

/*
Description:check if string is only number and letter
input?string
return: pass validation return true,otherwise false
*/
function isNumberOrLetter(s) {
    var regu = "^[0-9a-zA-Z]+$";
    var re = new RegExp(regu);
    return re.test(s);
}

/*
Description:check if string only include number,chinese and letter
input:string
return: pass validation return true,otherwise false
*/
function isChinaOrNumbOrLett(s) {
    var regu = "^[0-9a-zA-Z\u4e00-\u9fa5]+$";
    var re = new RegExp(regu);
    return re.test(s);
}

/*
Description:check if date is valid
input:date String,date formate
return: pass validation return true,otherwise false
*/
function isDate(date, fmt) {
    if (fmt == null) fmt = "yyyyMMdd";
    var yIndex = fmt.indexOf("yyyy");
    if (yIndex == -1) return false;
    var year = date.substring(yIndex, yIndex + 4);
    var mIndex = fmt.indexOf("MM");
    if (mIndex == -1) return false;
    var month = date.substring(mIndex, mIndex + 2);
    var dIndex = fmt.indexOf("dd");
    if (dIndex == -1) return false;
    var day = date.substring(dIndex, dIndex + 2);
    if (!isNumber(year) || year > "2100" || year < "1900") return false;
    if (!isNumber(month) || month > "12" || month < "01") return false;
    return !(day > getMaxDay(year, month) || day < "01");
}

function getMaxDay(year, month) {
    if (month == 4 || month == 6 || month == 9 || month == 11)
        return "30";
    if (month == 2)
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
            return "29";
        else
            return "28";
    return "31";
}

function isLastMatch(str1, str2)
{
    var index = str1.lastIndexOf(str2);
    return str1.length == index + str2.length;

}

function isFirstMatch(str1, str2)
{
    var index = str1.indexOf(str2);
    return index == 0;

}

function isMatch(str1, str2)
{
    var index = str1.indexOf(str2);
    return index != -1;

}

function checkTwoDate(startDate, endDate) {
    if (!isDate(startDate)) {
        return false;
    } else if (!isDate(endDate)) {
        return false;
    } else if (startDate > endDate) {
        return false;
    }
    return true;
}

function checkEmail(strEmail) {
    var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
    return emailReg.test(strEmail);
}

function checkPhone(strPhone) {
    var phoneRegWithArea = /^[0][1-9]{2,3}-[0-9]{5,10}$/;
    var phoneRegNoArea = /^[1-9]{1}[0-9]{5,8}$/;
    if (strPhone.length > 9) {
        return phoneRegWithArea.test(strPhone);
    } else {
        return phoneRegNoArea.test(strPhone);
    }
}

function checkSelect(checkboxID) {
    var check = 0;
    var i = 0;
    if (document.all(checkboxID).length > 0) {
        for (i = 0; i < document.all(checkboxID).length; i++) {
            if (document.all(checkboxID).item(i).checked) {
                check += 1;
            }
        }
    } else {
        if (document.all(checkboxID).checked)
            check = 1;
    }
    return check;
}

function getTotalBytes(varField) {
    if (varField == null)
        return -1;

    var totalCount = 0;
    for (i = 0; i < varField.value.length; i++) {
        if (varField.value.charCodeAt(i) > 127)
            totalCount += 2;
        else
            totalCount++;
    }
    return totalCount;
}

function getFirstSelectedValue(checkboxID) {
    var value = null;
    var i = 0;
    if (document.all(checkboxID).length > 0) {
        for (i = 0; i < document.all(checkboxID).length; i++) {
            if (document.all(checkboxID).item(i).checked) {
                value = document.all(checkboxID).item(i).value;
                break;
            }
        }
    } else {
        if (document.all(checkboxID).checked)
            value = document.all(checkboxID).value;
    }
    return value;
}

function getFirstSelectedIndex(checkboxID) {
    var value = -2;
    var i = 0;
    if (document.all(checkboxID).length > 0) {
        for (i = 0; i < document.all(checkboxID).length; i++) {
            if (document.all(checkboxID).item(i).checked) {
                value = i;
                break;
            }
        }
    } else {
        if (document.all(checkboxID).checked)
            value = -1;
    }
    return value;
}

function selectAll(checkboxID, status) {
    if (document.all(checkboxID) == null)
        return;

    if (document.all(checkboxID).length > 0) {
        for (var i = 0; i < document.all(checkboxID).length; i++) {
            document.all(checkboxID).item(i).checked = status;
        }
    } else {
        document.all(checkboxID).checked = status;
    }
}

function selectInverse(checkboxID) {
    if (document.all(checkboxID) == null)
        return;

    if (document.all(checkboxID).length > 0) {
        for (var i = 0; i < document.all(checkboxID).length; i++) {
            document.all(checkboxID).item(i).checked = !document.all(checkboxID).item(i).checked;
        }
    } else {
        document.all(checkboxID).checked = !document.all(checkboxID).checked;
    }
}

function checkDate(value) {
    if (value == '') return true;
    if (value.length != 8 || !isNumber(value)) return false;
    var year = value.substring(0, 4);
    if (year > "2100" || year < "1900") return false;

    var month = value.substring(4, 6);
    if (month > "12" || month < "01") return false;

    var day = value.substring(6, 8);
    return !(day > getMaxDay(year, month) || day < "01");
}

function checkPeriod(startDate, endDate) {
    if (!checkDate(startDate)) {
        return false;
    } else if (!checkDate(endDate)) {
        return false;
    } else if (startDate > endDate) {
        return false;
    }
    return true;
}

function checkSecCode(secCode) {
    if (secCode.length != 6) {
        return false;
    }
    return isNumber(secCode);
}

function cTrim(sInputString, iType)
{
    var sTmpStr = ' ';
    var i = -1;

    if (iType == 0 || iType == 1)
    {
        while (sTmpStr == ' ')
        {
            ++i;
            sTmpStr = sInputString.substr(i, 1);
        }
        sInputString = sInputString.substring(i);
    }
    if (iType == 0 || iType == 2)
    {
        sTmpStr = ' ';
        i = sInputString.length;
        while (sTmpStr == ' ')
        {
            --i;
            sTmpStr = sInputString.substr(i, 1);
        }
        sInputString = sInputString.substring(0, i + 1);
    }
    return sInputString;
}

function checkForm(objFrm) {
    var len = 0;
    len = objFrm.elements.length;

    var i = 0;
    var objCheck;

    for (i = 0; i < len; i ++) {
        objCheck = objFrm.elements[i];
        if (objCheck.type == "text" && !f_checkTextValid(objCheck)) {
            return false;
        }
    }

    for (i = 0; i < len; i ++) {
        objCheck = objFrm.elements[i];
        if (objCheck.type == "select-one" && !f_checkSelectValid(objCheck)) {
            return false;
        }
    }
    return f_checkStartAndEndDate(objFrm);
}

function f_checkSelectValid(obj) {
    return obj.options.length > 0;
}

function f_checkStartAndEndDate(frm) {
    var len = frm.elements.length;
    if (len == null && len == 0) return true;
    var i = 0;
    var temp;
    var objCheck;
    var objStartDate;
    var objEndDate;
    try {
        for (i = 0; i < len; i++) {
            objCheck = frm.elements[i];
            temp = objCheck.name;
            if (temp.indexOf("startDate") > 0 || temp.indexOf("beginDate") > 0)
                objStartDate = objCheck;
            if (temp.indexOf("endDate") > 0)
                objEndDate = objCheck;

        }
        if (objStartDate.value == null || objStartDate.value == "" || objStartDate.value == null || objStartDate.value == "") {
            return true;
        }
        return checkTwoDate(objStartDate.value, objEndDate.value);
    } catch(E) {
    }
    return true;
}

function f_checkTextValid(obj) {
    if (obj.getAttribute("isNeed") != null) {
        if (!f_isNotNull(obj)) return false;
    }
    if (obj.getAttribute("maxlength") != null) {
        if (!f_checkLength(obj)) return false;
    }
    var checkType = "";
    checkType = obj.getAttribute("checkType");
    if (checkType == null || checkType == "") return true;
    if (checkType.indexOf("number") >= 0) {
        if (!f_isNumber(obj))  return false;
        if (!f_checkNumType(obj, checkType))  return false;
    }
    if (checkType.indexOf("positive") >= 0) {
        if (!f_isNumber(obj))  return false;
        if (!f_isPositive(obj))  return false;
        if (!f_checkNumType(obj, checkType))  return false;
    }
    if (checkType.indexOf("date") >= 0) {
        if (!f_checkDate(obj)) return false;
    }
    return true;
}

function f_isNotNull(obj, msg) {
    if (obj.value == "") {
        f_alert(obj, msg);
        return false;
    }
    return true;
}

function f_isNumber(obj, msg) {
    if (isNaN(obj.value)) {
        f_alert(obj, msg);
        return false;
    }
    return true;

}
function f_checkDate(obj, msg) {
    if (!checkDate(obj.value)) {
        f_alert(obj, msg);
        return false;
    }
    return true;
}

function f_checkLength(obj, msg) {
    if (getTotalBytes(obj) > Math.abs(obj.getAttribute("maxlength"))) {
        f_alert(obj, msg);
        return false;
    }
    return true;

}

function f_alert(obj, alertStr) {
    var fielName = obj.getAttribute("fieldName");
    if (fielName == null)
        fielName = "";
    alert(fielName + "\n" + alertStr);
    obj.select();
    obj.focus();
}

function f_checkNumType(obj, numType) {
    var strTemp;
    var numpric;
    var numLen;
    var strArr;
    var defaultLen = 19;
    var defaultpric = 5;

    try {
        if (numType == null || numType == "") return f_checkNumLenPrec(obj, defaultLen, defaultpric);
        if (numType.indexOf("(") < 0 || numType.indexOf(")") < 0) return f_checkNumLenPrec(obj, defaultLen, defaultpric);
        strTemp = numType.substr(numType.indexOf("(") + 1, numType.indexOf(")") - numType.indexOf("(") - 1);
        if (strTemp == null || strTemp == "") return f_checkNumLenPrec(obj, defaultLen, defaultpric);
        strArr = strTemp.split(",");
        numLen = Math.abs(strArr[0]);
        numpric = Math.abs(strArr[1]);
        return f_checkNumLenPrec(obj, numLen, numpric);
    } catch(e) {
        alert("in f_checkNumType = " + e);
        return f_checkNumLenPrec(obj, defaultLen, defaultpric);
    }

}

function f_checkNumLenPrec(obj, len, pric) {
    var numReg;
    var value = obj.value;
    var strValueTemp, strInt, strDec;
    try {

        numReg = /[\-]/;
        strValueTemp = value.replace(numReg, "");
        strValueTemp = strValueTemp.replace(numReg, "");
        if (pric == 0) {
            numReg = /[\.]/;
            if (numReg.test(value)) {
                return false;
            }
        }

        if (strValueTemp.indexOf(".") < 0) {
            if (strValueTemp.length > ( len - pric)) {
                return false;
            }

        } else {
            strInt = strValueTemp.substr(0, strValueTemp.indexOf("."));
            if (strInt.length > ( len - pric)) {
                return false;
            }

            strDec = strValueTemp.substr((strValueTemp.indexOf(".") + 1), strValueTemp.length);
            if (strDec.length > pric) {
                return false;
            }
        }
        return true;
    } catch(e) {
        alert("in f_checkNumLenPrec = " + e);
        return false;
    }
}

function f_isPositive(obj, msg) {
    var numReg = /[\-]/;
    if (numReg.test(obj.value)) {
        f_alert(obj, msg);
        return false;
    }
    return true;

}

function selectedCheckboxCount(form) {
    var length = 0;
    var i = 0;
    var count = 0;
    var eles = form.elements;
    while (i < eles.length) {
        var obj = eles.item(i);
        var type = obj.type;
        if (type == "checkbox") {
            if (obj.checked) {
                count++;
            }
        }
        i++;
    }
    return count;
}

function getByteLen(str)
{
    var l = str.length;
    var n = l;
    for (var i = 0; i < l; i++)

        if (str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255)
            n = n + 1;
    return n
}

function clear_table(clearzero, tablename)
{
    var tobject;
    if (tablename == null)
        tobject = gmobj("sortTable");
    else
        tobject = gmobj(tablename);
    if (tobject == null)
        return;
    var clear = (clearzero == null) ? true : clearzero;
    var rows = tobject.rows;
    var j = 0;
    for (var i = 0; i < rows.length; i++)
    {
        while (tobject.rows[i].cells[j] != null)
        {
            if (clear)
            {
                if (tobject.rows[i].cells[j].innerHTML == 0 || tobject.rows[i].cells[j].innerHTML == 0.0 || tobject.rows[i].cells[j].innerHTML == "")
                    tobject.rows[i].cells[j].innerText = " ";
            }
            else
            {
                if (tobject.rows[i].cells[j].innerHTML == "")
                    tobject.rows[i].cells[j].innerText = " ";
            }
            j++;
        }
        j = 0;

    }
    return true;
}

function gmobj(mtxt) /* Get object by object name */
{
    if (document.getElementById) {
        m = document.getElementById(mtxt);
    } else if (document.all) {
        m = document.all[mtxt];
    } else if (document.layers) {
        m = document.layers[mtxt];
    }
    return m;
}


/*
    name:    Map.js
*/
function Node(key, value) {
    this.key = key;
    this.value = value;
}

function Map() {
    this.nodes = new Array();
}

Map.prototype.put = function(key, value) {
    for (var i = 0; i < this.nodes.length; i++)
        if (this.nodes[i].key == key) {
            this.nodes[i].value = value;
            return;
        }
    var node = new Node(key, value);
    this.nodes.push(node);
    return;
}


Map.prototype.get = function(key) {
    for (var i = 0; i < this.nodes.length; i++)
        if (this.nodes[i].key == key)
            return this.nodes[i].value;
    return null;
}

Map.prototype.size = function() {
    return this.nodes.length;
}


Map.prototype.clear = function() {
    while (this.nodes.length > 0)
        this.nodes.pop();
}

Map.prototype.remove = function(key) {
    for (var i = 0; i < this.nodes.length; i++)
        if (this.nodes[i].key == key) {
            var nodes1;
            if (i > 0)
                nodes1 = this.nodes.concat(this.nodes.slice(0, i - 1), this.nodes.slice(i + 1));
            else
                nodes1 = this.nodes.slice(1);
            this.nodes = nodes1;
        }
}


Map.prototype.isEmpty = function() {
    return this.nodes.length == 0;
}


Map.prototype.toString = function() {
    var str = "[";
    for (var i = 0; i < this.nodes.length; i++)
    {
        if (i < this.nodes.length - 1)
            str = str + this.nodes[i].key + ":" + this.nodes[i].value + "|";
        else
            str = str + this.nodes[i].key + ":" + this.nodes[i].value;
    }
    str = str + "]";
    return str;
}

//Dynamic loading(Compatible:IE7 and Firefox)
 onload = function()
{  
   alert(11);
   document.getElementById('someId').value="test";	 	
}





/** 
* 全选的所有指定名称的checkbox
*@state 全选的checkbox的状态
*@name   表格中的所有checkbox的名称
*@author fangtf
*@type void
*/
function selectAll(state,name) {
	var ids = document.getElementsByName(name);
	for (var i = 0; i < ids.length; i++) 
	{		
			ids[i].checked = state;
	}
}


/** 
* 全选的所有指定id名称的同名checkbox
*@state 全选的checkbox的状态
*@name   表格中的所有checkbox的名称
*@name   表格中的所有checkbox的id
*@author fangtf
*@type void
*/
function selectAllCheckboxByID(state,name,id) {
	var ids = document.getElementsByName(name);
	for (var i = 0; i < ids.length; i++) 
	{		
			if(ids[i].id == id)
			{
				ids[i].checked = state;
			}
			
	}
}

/** 
* 全选页面上所有的checkbox
*@state 全选的checkbox的状态
*@author fangtf
*@type void
*/
function selectAlls(state) 
{
	var inputs = document.getElementsByTagName("input");
	for(var i =0;i<inputs.length;i++)
	{
		if(inputs[i].type == "checkbox")
		{
			inputs[i].checked =state; 
		}
	}

}


/**
*得到鼠标所单击的行
*@type Object
*/
function GetRow(oElem) {
	while (oElem) {
		if (oElem.tagName.toLowerCase() == "tr" && oElem.parentElement.tagName.toLowerCase() == "tbody") {
			return oElem;
		}
		if (oElem.tagName.toLowerCase() == "table" || oElem.tagName.toLowerCase() == "th") {
			return false;
		}
		oElem = oElem.parentElement;
	}
}

/** 
* 全选当前行的checkbox
*@state 全选的checkbox的状态
*@author fangtf
*@type void
*/
function selectRowCheckbox(state)
{
  var row = GetRow(window.event.srcElement);
  var cells = row.childNodes; 
  for(var i=0;i<cells.length;i++)
  {
      var cell = cells[i].childNodes[0];
  	 if(cell.tagName == "INPUT")
  	 {
  	 	cell.checked = state;
  	 }
  }
}

/** 
*选中指定值的Radio
*如:有两个radio,
*第一个的name="ids",value="1"
*第二个的name="ids",value="2"
*调用方法selectRadio("ids","1");
*那么数值为1的Radio将被选中
*@name radio的名称
*@value radio的值
*@author fangtf
*@type void
*/
function selectRadio(name,value) {
    var radioObject = document.getElementsByName(name);
    if(value === "")
    {
    	radioObject[0].checked = true;
    	return;
    }
	for (var i = 0; i < radioObject.length; i++) 
	{
		if(radioObject[i].value == value)
		{
			radioObject[i].checked = true;
			break;
		}
		
	}
}


/** 
*选中指定值的checkbox
*如:有两个checkbox,
*第一个的name="ids",value="1"
*第二个的name="ids",value="2"
*第三个的name="ids",value="3"
*调用这个方法selectCheckbox("ids","1,2")那么数值为1,2的checkbox将被选中
*                
*@name 要选中的checkbox数组的名称
*@value 判断时候选中的值
*@author fangtf
*@type void
*/
function selectCheckbox(name,value) {
    var checkObject = document.getElementsByName(name);
    var values = value.split(",");
    for(var j = 0; j < values.length; j++)
    {
    	for (var i = 0; i < checkObject.length; i++) 
		{
			if(checkObject[i].value == values[j])
			{
				checkObject[i].checked = true;
				break;
			}
		}
    }
	
}

/** 
*选中指定值的select
*如:有一个名称为user的select
*<option value="0"></option>
*<option value="1"></option>
*调用这个方法selectOption("user","0")那么选项为0的选项就被选中
*               
*@name  String  select的名称
*@value String  判断时候选中的值
*@author fangtf
*@type void
*/
function selectOption(name,value)
{
     document.getElementsByName(name)[0].value=value;

}




/**   
*得到现在的日期 
* 
*@author fangtf  
*@type string  
*/ 
function getNowTime() 
{ 
  var date = new Date(); 

  var d= date.getDate(); 

  var day = (d < 10) ? '0' + d : d; 

  var m = date.getMonth() + 1; 

  var month = (m < 10) ? '0' + m : m; 

  var yy = date.getYear(); 

  var year = (yy < 1000) ? yy + 1900 : yy; 
  
  var hh = date.getHours(); 
  
  var hh = (hh < 10) ? '0' + hh : hh; 
  
  var mm = date.getMinutes(); 
  
  var mm = (mm < 10) ? '0' + mm : mm; 
   
  return (year + "-" + month + "-" +day+" "+hh+":"+mm); 
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics