网页输入框日期型有效性判定一网打尽
网页输入框日期型有效性判定一网打尽 [著者]zosatapo
[联系]dertyang@263.net
我利用正则表达式写的日期型网页输入框数据是否有效的判定函数。
包含闰年的处理,有兴趣正则表达式的同行,以及需要对网页中日期进行
很好判定的朋友可以参照一下。同时函数支持自我日期输入形式定义。
1#辅助函数(闰年判定)
function isLeapYear(year)
{
if((year%4==0&&year%100!=0)||(year%400==0))
{
return true;
}
return false;
}
2#判定主函数
function dateValidation(object,format)
{
var regexp,value,index;
var year,month,day;
var iyear,imonth,iday;
var fmt,regfmt,ordfmt;
var dateArray;
if(isObject(object))
{
value=object.value;
}
else if(isString(object)&&!isEmpty(object))
{
value=object;
}
else
{
return false;
}
if(isEmpty(format))
{
return false;
}
fmt=new Array("yyyy/mm/dd","mm/dd/yyyy","dd/mm/yyyy");
regfmt=new Array("/^([0-9]{4})\\/([0-9]{2})\\/([0-9]{2})$/","/^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$/","/^([0-9]{2})\\/([0-9]{2})\\/([0-9]{4})$/");
ordfmt=new Array("123","312","321");
format=format.toLowerCase();
for(index=0;index<fmt.length;index++)
{
if(format==fmt[index])
{
eval('regexp='+regfmt[index]+';');
iyear=parseInt(ordfmt[index].charAt(0));
imonth=parseInt(ordfmt[index].charAt(1));
iday=parseInt(ordfmt[index].charAt(2));
break;
}
}
if(index==fmt.length)
{
alert("Date Format Not Supported!");
return false;
}
if(regexp.test(value)){
//alert("Date is matched with Format!");
dateArray=value.match(regexp);
year=dateArray[iyear];
month=dateArray[imonth];
day=dateArray[iday];
//alert("The Date you have filled is:\nYear:"+year+"\nMonth:"+month+"\nDay:"+day);
if(year<2001)
{
alert("Year must be greater than 2001!");
return false;
}
if(month<0||month>12)
{
alert("Month must range from 1 to 12!");
return false;
}
if(day<0||day>31)
{
alert("Day must range from 1 to 31!");
return false;
}
else
{
if(month==2)
{
if(isLeapYear(year)&&day>29)
{
alert("In Month 2,Day must range from 1 to 29!");
return false;
}
if(!isLeapYear(year)&&day>28)
{
alert("In Month 2,Day must range from 1 to 28!");
return false;
}
}
if((month==4||month==6||month==9||month==11)&&(day>30))
{
alert("In this Month ,Day must range from 1 to 30!");
return false;
}
}
}
else
{
alert("Date isn't matched with Format!\nDate Format:"+format);
return false;
}
return true;
}