JavaScript 常用脚本

 //清除左边空格
        function js_ltrim(deststr) {
            if (deststr == null) return "";
            var pos = 0;
            var retStr = new String(deststr);
            if (retStr.lenght == 0) return retStr;
            while (retStr.substring(pos, pos + 1) == " ") pos++;
            retStr = retStr.substring(pos);
            return (retStr);
        }
        //清除右边空格
        function js_rtrim(deststr) {
            if (deststr == null) return "";
            var retStr = new String(deststr);
            var pos = retStr.length;
            if (pos == 0) return retStr;
            while (pos && retStr.substring(pos - 1, pos) == " ") pos--;
            retStr = retStr.substring(0, pos);
            return (retStr);
        }
        //清除左边和右边空格
        function js_trim(deststr) {
            if (deststr == null) return "";
            var retStr = new String(deststr);
            var pos = retStr.length;
            if (pos == 0) return retStr;
            retStr = js_ltrim(retStr);
            retStr = js_rtrim(retStr);
            return retStr;
        }

1、数字验证内
    1.1 整数
        /^(-|+)?d+$/.test(str)
    1.2 大于0的整数 (用于传来的ID的验证)
        /^d+$/.test(str)
    1.3 负整数的验证
        /^-d+$/.test(str)
2、时间类
    2.1 短时间,形如 (13:04:06)
        function isTime(str)
        {
          var a = str.match(/^(d{1,2})(:)?(d{1,2})2(d{1,2})$/);
          if (a == null) {alert('输入的参数不是时间格式'); return false;}
          if (a[1]>24 || a[3]>60 || a[4]>60)
          {
            alert("时间格式不对");
            return false
          }
          return true;
        }
    2.2 短日期,形如 (2003-12-05)
        function strDateTime(str)
        {
           var r = str.match(/^(d{1,4})(-|/)(d{1,2})2(d{1,2})$/);
           if(r==null)return false;
           var d= new Date(r[1], r[3]-1, r[4]);
           return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
        }
    2.3 长时间,形如 (2003-12-05 13:04:06)
        function strDateTime(str)
        {
          var reg = /^(d{1,4})(-|/)(d{1,2})2(d{1,2}) (d{1,2}):(d{1,2}):(d{1,2})$/;
          var r = str.match(reg);
          if(r==null)return false;
          var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
         return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
        }
    2.4 只有年和月。形如(2003-05,或者2003-5)
    2.5 只有小时和分钟,形如(12:03)
3、表单类
    3.1 所有的表单的值都不能为空
        <input onblur="if(this.value.replace(/^s+|s+$/g,'')=='')alert('不能为空!')">
    3.2 多行文本框的值不能为空。
    3.3 多行文本框的值不能超过sMaxStrleng
    3.4 多行文本框的值不能少于sMixStrleng
    3.5 判断单选框是否选择。
    3.6 判断复选框是否选择.
    3.7 复选框的全选,多选,全不选,反选
    3.8 文件上传过程中判断文件类型
4、字符类
    4.1 判断字符全部由a-Z或者是A-Z的字字母组成
        <input onblur="if(/[^a-zA-Z]/g.test(this.value))alert('有错')">
    4.2 判断字符由字母和数字组成。
        <input onblur="if(/[^0-9a-zA-Z]/g.test(this.value))alert('有错')">
    4.3 判断字符由字母和数字,下划线,点号组成.且开头的只能是下划线和字母
        /^([a-zA-z_]{1})([w]*)$/g.test(str)
    4.4 字符串替换函数.Replace();
5、浏览器类
    5.1 判断浏览器的类型
        window.navigator.appName
    5.2 判断ie的版本
        window.navigator.appVersion
    5.3 判断客户端的分辨率
        window.screen.height;   window.screen.width;
  
6、结合类
    6.1 email的判断。
        function ismail(mail)
        {
          return(new RegExp(/^w+((-w+)|(.w+))*@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$/).test(mail));
        }
    6.2 手机号码的验证
    6.3 身份证的验证
        function isIdCardNo(num)
        {
          if (isNaN(num)) {alert("输入的不是数字!"); return false;}
          var len = num.length, re;
          if (len == 15)
            re = new RegExp(/^(d{6})()?(d{2})(d{2})(d{2})(d{3})$/);
          else if (len == 18)
            re = new RegExp(/^(d{6})()?(d{4})(d{2})(d{2})(d{3})(d)$/);
          else {alert("输入的数字位数不对!"); return false;}
          var a = num.match(re);
          if (a != null)
          {
            if (len==15)
            {
              var D = new Date("19"+a[3]+"/"+a[4]+"/"+a[5]);
              var B = D.getYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
            }
            else
            {
              var D = new Date(a[3]+"/"+a[4]+"/"+a[5]);
              var B = D.getFullYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
            }
            if (!B) {alert("输入的身份证号 "+ a[0] +" 里出生日期不对!"); return false;}
          }
          return true;
        }

3.7 复选框的全选,多选,全不选,反选
<form name=hrong>
<input type=checkbox name=All onclick="checkAll('mm')">全选<br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/>
<input type=checkbox name=mm onclick="checkItem('All')"><br/><br/>


<input type=checkbox name=All2 onclick="checkAll('mm2')">全选<br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>
<input type=checkbox name=mm2 onclick="checkItem('All2')"><br/>

</form>

<SCRIPT LANGUAGE="JavaScript">
function checkAll(str)
{
    var a = document.getElementsByName(str);
    var n = a.length;
    for (var i=0; i<n; i++)
    a[i].checked = window.event.srcElement.checked;
}
function checkItem(str)
{
    var e = window.event.srcElement;
    var all = eval("document.hrong."+ str);
    if (e.checked)
    {
      var a = document.getElementsByName(e.name);
      all.checked = true;
      for (var i=0; i<a.length; i++)
      {
        if (!a[i].checked){ all.checked = false; break;}
      }
    }
    else all.checked = false;
}
</SCRIPT>

3.8 文件上传过程中判断文件类型
<input type=file onchange="alert(this.value.match(/^(.*)(.)(.{1,8})$/)[3])">

画图:
<OBJECT
id=S
style="LEFT: 0px; WIDTH: 392px; TOP: 0px; HEIGHT: 240px"
height=240
width=392
classid="clsid:369303C2-D7AC-11D0-89D5-00A0C90833E6">
</OBJECT>
<SCRIPT>
S.DrawingSurface.ArcDegrees(0,0,0,30,50,60);
S.DrawingSurface.ArcRadians(30,0,0,30,50,60);
S.DrawingSurface.Line(10,10,100,100);
</SCRIPT>

写注册表:
<SCRIPT>
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.RegWrite ("HKCUSoftwareACMEFortuneTeller", 1, "REG_BINARY");
WshShell.RegWrite ("HKCUSoftwareACMEFortuneTellerMindReader", "Goocher!", "REG_SZ");
var bKey =     WshShell.RegRead ("HKCUSoftwareACMEFortuneTeller");
WScript.Echo (WshShell.RegRead ("HKCUSoftwareACMEFortuneTellerMindReader"));
WshShell.RegDelete ("HKCUSoftwareACMEFortuneTellerMindReader");
WshShell.RegDelete ("HKCUSoftwareACMEFortuneTeller");
WshShell.RegDelete ("HKCUSoftwareACME");
</SCRIPT>

TABLAE相关(客户端动态增加行列)
<HTML>
<SCRIPT LANGUAGE="JScript">
function numberCells() {
      var count=0;
      for (i=0; i < document.all.mytable.rows.length; i++) {
          for (j=0; j < document.all.mytable.rows(i).cells.length; j++) {
              document.all.mytable.rows(i).cells(j).innerText = count;
              count++;
          }
      }
}
</SCRIPT>
<BODY onload="numberCells()">
<TABLE id=mytable border=1>
<TR><TH> </TH><TH> </TH><TH> </TH><TH> </TH></TR>
<TR><TD> </TD><TD> </TD><TD> </TD><TD> </TD></TR>
<TR><TD> </TD><TD> </TD><TD> </TD><TD> </TD></TR>
</TABLE>
</BODY>
</HTML>

1.身份证严格验证:

<script>
var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新_疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
  
function cidInfo(sId){
   var iSum=0
   var info=""
   if(!/^d{17}(d|x)$/i.test(sId))return false;
   sId=sId.replace(/x$/i,"a");
   if(aCity[parseInt(sId.substr(0,2))]==null)return "Error:非法地区";
   sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
   var d=new Date(sBirthday.replace(/-/g,"/"))
   if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "Error:非法生日";
   for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11)
   if(iSum%11!=1)return "Error:非法证号";
   return aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女")
}

document.write(cidInfo("380524198002300016"),"<br/>");
document.write(cidInfo("340524198002300019"),"<br/>")
document.write(cidInfo("340524197711111111"),"<br/>")
document.write(cidInfo("34052419800101001x"),"<br/>");
</script>

2.验证IP地址
<SCRIPT LANGUAGE="JavaScript">
function isip(s){
   var check=function(v){try{return (v<=255 && v>=0)}catch(x){return false}};
   var re=s.split(".")
   return (re.length==4)?(check(re[0]) && check(re[1]) && check(re[2]) && check(re[3])):false
}

var s="202.197.78.129";
alert(isip(s))
</SCRIPT>

 

 

3.加sp1后还能用的无边框窗口!!
<HTML XMLNS:IE>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<IE:Download ID="include" STYLE="behavior:url(#default#download)" />
<title>Chromeless Window</title>

<SCRIPT LANGUAGE="JScript">
/*--- Special Thanks For andot ---*/

/*
 This following code are designed and writen by Windy_sk <[email protected]>
 You can use it freely, but u must held all the copyright items!
*/

/*--- Thanks For andot Again ---*/

var CW_width = 400;
var CW_height = 300;
var CW_top = 100;
var CW_left = 100;
var CW_url = "/";
var New_CW = window.createPopup();
var CW_Body = New_CW.document.body;
var content = "";
var CSStext = "margin:1px;color:black; border:2px outset;border-style:expression(onmouseout=onmouseup=function(){this.style.borderStyle='outset'}, onmousedown=function(){if(event.button!=2)this.style.borderStyle='inset'});background-color:buttonface;width:16px;height:14px;font-size:12px;line-height:11px;cursor:Default;";

//Build Window
include.startDownload(CW_url, function(source){content=source});

function insert_content(){
 var temp = "";
 CW_Body.style.overflow  = "hidden";
 CW_Body.style.backgroundColor = "white";
 CW_Body.style.border  =  "solid black 1px";
 content = content.replace(/<a ([^>]*)>/g,"<a onclick='parent.open(this.href);return false' $1>");
 temp += "<table width=100% height=100% cellpadding=0 cellspacing=0 border=0>";
 temp += "<tr style=';font-size:12px;background:#0099CC;height:20;cursor:default' ondblclick=\"Max.innerText=Max.innerText=='1'?'2':'1';parent.if_max=!parent.if_max;parent.show_CW();\" onmouseup='parent.drag_up(event)' onmousemove='parent.drag_move(event)' onmousedown='parent.drag_down(event)' onselectstart='return false' oncontextmenu='return false'>";
 temp += "<td style='color:#ffffff;padding-left:5px'>Chromeless Window For IE6 SP1</td>";
 temp += "<td style='color:#ffffff;padding-right:5px;' align=right>";
 temp += "<span id=Help  onclick=\"alert('Chromeless Window For IE6 SP1  -  Ver 1.0\\n\\nCode By Windy_sk\\n\\nSpecial Thanks For andot')\" style=\""+CSStext+"font-family:System;padding-right:2px;\">?</span>";
 temp += "<span id=Min   onclick='parent.New_CW.hide();parent.blur()' style=\""+CSStext+"font-family:Webdings;\" title='Minimum'>0</span>";
 temp += "<span id=Max   onclick=\"this.innerText=this.innerText=='1'?'2':'1';parent.if_max=!parent.if_max;parent.show_CW();\" style=\""+CSStext+"font-family:Webdings;\" title='Maximum'>1</span>";
 temp += "<span id=Close onclick='parent.opener=null;parent.close()' style=\""+CSStext+"font-family:System;padding-right:2px;\" title='Close'>x</span>";
 temp += "</td></tr><tr><td colspan=2>";
 temp += "<div id=include style='overflow:scroll;overflow-x:hidden;overflow-y:auto; HEIGHT: 100%; width:"+CW_width+"'>";
 temp += content;
 temp += "</div>";
 temp += "</td></tr></table>";
 CW_Body.innerHTML = temp;
}

setTimeout("insert_content()",1000);

var if_max = true;
function show_CW(){
 window.moveTo(10000, 10000);
 if(if_max){
  New_CW.show(CW_top, CW_left, CW_width, CW_height);
  if(typeof(New_CW.document.all.include)!="undefined"){
   New_CW.document.all.include.style.width = CW_width;
   New_CW.document.all.Max.innerText = "1";
  }
 
 }else{
  New_CW.show(0, 0, screen.width, screen.height);
  New_CW.document.all.include.style.width = screen.width;
 }
}

window.onfocus  = show_CW;
window.onresize = show_CW;

// Move Window
var drag_x,drag_y,draging=false

function drag_move(e){
 if (draging){
  New_CW.show(e.screenX-drag_x, e.screenY-drag_y, CW_width, CW_height);
  return false;
 }
}

function drag_down(e){
 if(e.button==2)return;
 if(New_CW.document.body.offsetWidth==screen.width && New_CW.document.body.offsetHeight==screen.height)return;
 drag_x=e.clientX;
 drag_y=e.clientY;
 draging=true;
 e.srcElement.setCapture();
}

function drag_up(e){
 draging=false;
 e.srcElement.releaseCapture();
 if(New_CW.document.body.offsetWidth==screen.width && New_CW.document.body.offsetHeight==screen.height) return;
 CW_top  = e.screenX-drag_x;
 CW_left = e.screenY-drag_y;
}

</SCRIPT>
</HTML>

 

 

三個實用的小技巧:關閉輸入法.禁止貼上.禁止複製
關閉輸入法

本文字框輸入法被關閉: 
語法: style="ime-mode:disabled"
範例: <input type="text" name="textfield" style="ime-mode:disabled">

禁止貼上

本文字框禁止貼上文字: 
語法:onpaste="return false"
範例:<input type="text" name="textfield" onpaste="return false">

禁止複製

本文字框禁止複製: 
語法:oncopy="return false;" oncut="return false;"
範例:<input name="textfield" type="text" value="不能複製裡面的字" oncopy="return false;" oncut="return false;">


 

//================================
//Cookie操作
//================================
function getCookieVal (offset)
{
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

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 getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0)
break;
}
return null;
}


function deleteCookie(cname) {

  var expdate = new Date();
  expdate.setTime(expdate.getTime() - (24 * 60 * 60 * 1000 * 369));

 // document.cookie =" ckValue="ok"; expires="+ expdate.toGMTString();
  setCookie(cname,"",expdate);

}

function setCookie (name, value, expires) {

  document.cookie = name + "=" + escape(value) +
    "; expires=" + expires.toGMTString() ;
}

 

 

 

javascript正则表达式检验
/*********************************************************************************
* EO_JSLib.js
* javascript正则表达式检验
**********************************************************************************/

//校验是否全由数字组成
function isDigit(s)
{
var patrn=/^[0-9]{1,20}$/;
if (!patrn.exec(s)) return false
return true
}

//校验登录名:只能输入5-20个以字母开头、可带数字、“_”、“.”的字串
function isRegisterUserName(s)
{
var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
if (!patrn.exec(s)) return false
return true
}

//校验用户姓名:只能输入1-30个以字母开头的字串
function isTrueName(s)
{
var patrn=/^[a-zA-Z]{1,30}$/;
if (!patrn.exec(s)) return false
return true
}

//校验密码:只能输入6-20个字母、数字、下划线
function isPasswd(s)
{
var patrn=/^(\w){6,20}$/;
if (!patrn.exec(s)) return false
return true
}

//校验普通电话、传真号码:可以“+”开头,除数字外,可含有“-”
function isTel(s)
{
//var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?(\d){1,12})+$/;
var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
if (!patrn.exec(s)) return false
return true
}

//校验手机号码:必须以数字开头,除数字外,可含有“-”
function isMobil(s)
{
var patrn=/^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
if (!patrn.exec(s)) return false
return true
}

//校验邮政编码
function isPostalCode(s)
{
//var patrn=/^[a-zA-Z0-9]{3,12}$/;
var patrn=/^[a-zA-Z0-9 ]{3,12}$/;
if (!patrn.exec(s)) return false
return true
}

//校验搜索关键字
function isSearch(s)
{
var patrn=/^[^`~!@#$%^&*()+=|\\\][\]\{\}:;'\,.<>/?]{1}[^`~!@$%^&()+=|\\\][\]\{\}:;'\,.<>?]{0,19}$/;
if (!patrn.exec(s)) return false
return true
}

function isIP(s) //by zergling
{
var patrn=/^[0-9.]{1,20}$/;
if (!patrn.exec(s)) return false
return true
}


 

! 去除字符串两端空格的处理

如果采用传统的方式,就要可能就要采用下面的方式了
//清除左边空格
function js_ltrim(deststr)
{
 if(deststr==null)return "";
 var pos=0;
 var retStr=new String(deststr);
 if (retStr.lenght==0) return retStr;
 while (retStr.substring(pos,pos+1)==" ") pos++;
 retStr=retStr.substring(pos);
 return(retStr);
}
//清除右边空格
function js_rtrim(deststr)
{
 if(deststr==null)return "";
 var retStr=new String(deststr);
 var pos=retStr.length;
 if (pos==0) return retStr;
 while (pos && retStr.substring(pos-1,pos)==" " ) pos--;
 retStr=retStr.substring(0,pos);
 return(retStr);
}
//清除左边和右边空格
function js_trim(deststr)
{
 if(deststr==null)return "";
 var retStr=new String(deststr);
 var pos=retStr.length;
 if (pos==0) return retStr;
 retStr=js_ltrim(retStr);
 retStr=js_rtrim(retStr);
 return retStr;
}

采用正则表达式,来去除两边的空格,只需以下代码
String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}

一句就搞定了,
可见正则表达式为我们节省了相当的编写代码量


! 移动手机号的校验

如果采用传统的校验方式至少就要完成下面三步的校验,
(1). 是否是数字
(2).是否是11位
(3).数字的第三位是否是5,6,7,8,9
如果采用正则表达式校验,只需以下代码
function checkMobile1(form)
{
if (form.mobile.value > "")
{
var reg=/13[5,6,7,8,9]\d{8}/;
if ( form.mobile.value.match(reg)== null)
{
alert("请输入正确的移动手机号码!");
form.mobile.focus(); return false;
 }
}
return true;
}

从上面的代码可以看出校验移动手机号只需定义一个var reg=/13[5,6,7,8,9]\d{8}/;模式匹配串就可以完成合法性校验了

! URL的校验,
条件:必须以http:// 或 https:// 开头, 端口号必须为在1-65535 之间, 以下代码完成了合法性校验

//obj:数据对象
//dispStr :失败提示内容显示字符串
function checkUrlValid( obj,  dispStr)
{
 if(obj  == null)
 {
  alert("传入对象为空");
  return false;
 }
 var str = obj.value;

 var  urlpatern0 = /^https?:\/\/.+$/i;
 if(!urlpatern0.test(str))
 {
  alert(dispStr+"不合法:必须以'http:\/\/'或'https:\/\/'开头!");
  obj.focus();
  return false;
 }

 var  urlpatern2= /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?.+$/i;
 if(!urlpatern2.test(str))
 {
  alert(dispStr+"端口号必须为数字且应在1-65535之间!");
  obj.focus();
  return false;
 }


 var urlpatern1 =/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;

 if(!urlpatern1.test(str))
 {
  alert(dispStr+"不合法,请检查!");
  obj.focus();
  return false;
 }

 var s = "0";
 var t =0;
  var re = new RegExp(":\\d+","ig");
  while((arr = re.exec(str))!=null)
 {
  s = str.substring(RegExp.index+1,RegExp.lastIndex);

  if(s.substring(0,1)=="0")
  {
   alert(dispStr+"端口号不能以0开头!");
   obj.focus();
   return false;
  }

  t = parseInt(s);
  if(t<1 || t >65535)
  {
   alert(dispStr+"端口号必须为数字且应在1-65535之间!");
   obj.focus();
   return false;
  }
 }
 return true;
}
 
对url的校验,看上去有很多的代码,这是因为要给予出错提示, 否则只需var urlpatern1 =/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i; 一句就可以校验出url合法性了

 


 

 

 

你可能感兴趣的:(JavaScript)