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

js验证是否为空、数字、邮政编码、联系电话、传真、电子邮箱格式(公用js)
//自定义扩展方法,供外部调用
String.prototype.isNull = testNull;//判断是否为空
String.prototype.number = testNumber;//判断数字,只能为整数
String.prototype.doubleNumber = testDoubleNumber;//判断数字,可以为小数
String.prototype.zip = testZip;//判断邮政编码格式
String.prototype.phone = testPhoneNumber;//判断联系电话、传真格式
String.prototype.email = testEmail;//判断电子邮箱格式
//判断是否为空,为空则返回true
function testNull(){
if(this.replace(/(^\s*)|(\s*$)/g, '').length<=0)
{//为空
   return true;
}
else{//不为空
   return false;
}
}
//判断是否为数字,是数字则返回true
function testNumber()
{
if(!this.isNull()){
   for(i=0;i<this.length;i++)
   {
    if(this.charAt(i)<"0"||this.charAt(i)>"9")
    {
     return false;
    }
   }
   return true;
}
else
{
   return true;
}
}
//判断邮政编码格式,格式正确返回true
function testZip()
{
if(!this.isNull()){
   if(this.length!=6)
   {
    return false;
   }
   else
   {
    var rexTel=/^[0-9]+$/;
    if(!rexTel.test(this))
    {
     return false;
    }
   }
}
return true;
}
//判断联系电话、传真格式,格式正确返回true
function testPhoneNumber()
{
if(!this.isNull()){
   var reg=/(^[0-9]{3,4}\-[0-9]{7,8}\-[0-9]{3,4}$)|(^[0-9]{3,4}\-[0-9]{7,8}$)|(^[0-9]{7,8}\-[0-9]{3,4}$)|(^[0-9]{7,15}$)/;
   if(!reg.test(this))
   {
    return false;
   }
   return true;
}
else
{
   return true;
}
}
//判断电子邮箱格式,格式正确返回true
function testEmail()
{
if(!this.isNull()){
   if(this.search(/^([-_A-Za-z0-9\.]+)@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/)!=-1)
   {
    return true;
   }
   else
   {
    return false;
   }
}
else
{
   return true;
}
}
//判断是否是数字,可以为小数,格式正确返回true
function testDoubleNumber()
{
var pointCount=0;
for(var i=0;i<this.length;i++){
   if((this.charAt(i)<'0'||this.charAt(i)>'9')&&this.charAt(i)!='.'){
    return false;
   }
   else{
    if(this.charAt(i)=='.')pointCount++;
   }
}
if(pointCount>1){
   return false;
}else if(pointCount==1&&this.trim().length==1){
   return false;
}
return true;
}