//验证日期格式为 yyyy/MM/dd 或 yyyy-MM-dd
//验证日期格式为 yyyy/MM/dd
//验证日期格式为 yyyy-mm-dd 只需改 reg \/ 为 - split("/") 为 split("-");
function checkDate(theDate){
var reg = /^\d{4}\/((0{0,1}[1-9]{1})|(1[0-2]{1}))\/((0{0,1}[1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1}))$/;
//小于10都需要加0
//var reg = /^\d{4}\/((0[1-9]{1})|(2[0-2]{1}))\/((0[1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1}))$/;
var reg2 = /^\d{4}-((0{0,1}[1-9]{1})|(1[0-2]{1}))-((0{0,1}[1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1}))$/;
var result=true;
if(!reg.test(theDate) && !reg2.test(theDate))
result = false;
else{
// var arr_hd=theDate.split("/");
var arr_hd;
if(theDate.indexOf("/") != -1){
arr_hd=theDate.split("/");
}else if(theDate.indexOf("-") != -1){
arr_hd=theDate.split("-");
}
var dateTmp;
dateTmp= new Date(arr_hd[0],parseFloat(arr_hd[1])-1,parseFloat(arr_hd[2]));
//alert(arr_hd[0]+" "+parseFloat(arr_hd[1])-1 +" "+parseFloat(arr_hd[2]));
// alert("dateTmp: "+dateTmp);
if(dateTmp.getFullYear()!=parseFloat(arr_hd[0])
|| dateTmp.getMonth()!=parseFloat(arr_hd[1]) -1
|| dateTmp.getDate()!=parseFloat(arr_hd[2])){
result = false
}
}
return result;
}
//alert("checkresult: "+checkDate("2001/05/30"));
var a="2010-8-9";
// alert("replace method: "+a.replace(/-/g, "/"));
//a=a.replace(/-/g,"/");
//alert(a);
//将日期 2010-8-9转换为 2010-08-09
if(a.indexOf("-") != -1){
var ab = a.split("-", 3);
for(var i =0; i<ab.length;i++ ){
if(ab[i].length<2){
ab[i]="0"+ab[i];
}
}
// alert(ab.join("/"));//转换日期为 2010/08/09
}
function checkDate2(inputDateObj){
// alert(inputDate);
var inputDate = inputDateObj.value;
if(checkDate(inputDate)){
inputDateObj.style.border="";
if(inputDate.indexOf("-") !=-1){
inputDate = inputDate.replace(/-/g,'/');
}
var inputdate = inputDate.split("/",3);
for(var i = 0; i< inputdate.length; i++ ){
if(inputdate[i].length<2){
inputdate[i]="0"+inputdate[i];
}
}
// alert(inputdate.join("/"));
}else{
inputDateObj.style.border="solid 2px red";
inputDateObj.focus();
}
}
javascript date 验证yyyy/MM/dd yyyy-MM-dd
最新推荐文章于 2023-09-03 14:19:15 发布