日期:2014-05-16  浏览次数:20358 次

js去掉空格键和js过滤特殊字符
过滤空格键
<script>
function trim(inputString) {
               //xiao duan 22/06/2007 
              if (typeof inputString != "string") { return inputString; }
              var retValue = inputString;
              var ch = retValue.substring(0, 1);
              while (ch == " ") { 
           //检查字符串开始部分的空格
                  retValue = retValue.substring(1, retValue.length);
                  ch = retValue.substring(0, 1);
              }
              ch = retValue.substring(retValue.length-1, retValue.length);
              while (ch == " ") {
                 //检查字符串结束部分的空格
                 retValue = retValue.substring(0, retValue.length-1);
                 ch = retValue.substring(retValue.length-1, retValue.length);
              }
              while (retValue.indexOf("  ") != -1) { 
          //将文字中间多个相连的空格变为一个空格
                 retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); 
              }
              return retValue;
           }

//--> 
</script>

//过滤特殊字符
<script>
function CheckIfEnglish( String )
{ 
    var Letters = "(!@#$%^&*;':)";
     var i;
     var c;
      if(String.charAt( 0 )=='-')
 return false;
      if( String.charAt( String.length - 1 ) == '-' )
          return false;
 for( i = 0; i < String.length; i ++ )
     {
          c = String.charAt( i );
   if (Letters.indexOf( c ) > 0)
    return false;        
     }
     return true;
}
</script>

<script language="javascript">
//更多的过滤字符,请自己补充到new Array("char","varcahr","#"); 
function checkForms()
{
   var iu, iuu, regArray=new Array("char","varcahr","#","admin"); 
   iuu=regArray.length;
   var obj=document.getElementById("username");
   if(obj.value=="")
   {
     alert("用户名不能为空");
      obj.focus();
      return false;
   }
   for(iu=1;iu<=iuu;iu++)
   {   
      if(regArray[iu] !="")
       {
          if (obj.value.indexOf(regArray[iu])!=-1)
           {
             alert("注册名不可以包含:" + regArray[iu]);
             document.Gforms.username.focus();
             return false;
          }
        }
   }
   return true;              
}
</script>

<form method="post" onSubmit="return checkForms();">
请输入用户名:<input type="text" name="username">
<input type="submit" name="Submit" value="提交"> 
</form>