JS检查表单

来源:互联网 发布:知枢密院事 编辑:程序博客网 时间:2024/06/05 13:34

首现是根据id获取表单的值:

var num = document.getElementById(ElementId).value;

1、检查是否为空:

num.length <= 0

2、检查是否是数字(包括小数):

isNaN(num):

如果if(isNaN(num))则返回false,表示非数字

3、检查邮箱是否正确:

function chkemail(str)//判断邮箱格式是否正确
{
     return str.search(/[\w\-]{1,}@[\w\-]{1,}\.[\w\-]{1,}/)==0?true:false
}

4、检查两个日期的先后顺序:

<html> <head>  <script language="javascript" type="text/javascript">   /** 日期比较 **/   function compareDate(strDate1,strDate2)   {    var date1 = new Date(strDate1.replace(/\-/g, "\/"));    var date2 = new Date(strDate2.replace(/\-/g, "\/"));    return date1-date2;   }      /** 比较 **/   function doCompare(){    var strDate1 = document.getElementById("strDate1").value;    var strDate2 = document.getElementById("strDate2").value;    var result = compareDate(strDate1,strDate2);    if ( result>0 ) {     alert("strDate1晚于strDate2");    }else if( result<0 ){     alert("strDate1早于strDate2");    }else if ( result==0 ){     alert("strDate1等于strDate2");    }   }  </script> </head> <body>  <input type="text" id="strDate1" name="strDate1" value="2012-07-01"/>  <input type="text" id="strDate2" name="strDate2" value="2012-08-01"/>  <input type="button" id="compareBtn" name="compareBtn" value="比较" onClick="doCompare();"/> </body></html>