📜  验证日期 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:51.508000             🧑  作者: Mango

代码示例2
function validatedate(inputText,DateFormat)
{
// format dd/mm/yyyy or in any order of (dd or mm or yyyy) you can write dd or mm or yyyy in first or second or third position ... or can be slash"/" or dot"." or dash"-" in the dates formats
var invalid = "";
var dt = "";
var mn = "";
var yr = "";
var k;
var delm = DateFormat.includes("/") ? "/" : ( DateFormat.includes("-") ? "-" : ( DateFormat.includes(".") ? "." : "" ) ) ;
var f1 = inputText.split(delm);
var f2 = DateFormat.split(delm);
for(k=0;k<=2;k++)
{ 
 dt = dt + (f2[parseInt(k)]=="dd" ? f1[parseInt(k)] : "");
 mn = mn + (f2[parseInt(k)]=="mm" ? f1[parseInt(k)] : "");
 yr = yr + (f2[parseInt(k)]=="yyyy" ? f1[parseInt(k)] : "");
}
var mn_days = "0-31-" + (yr % 4 == 0 ? 29 : 28) + "-31-30-31-30-31-31-30-31-30-31";
var days = mn_days.split("-");
if( f1.length!=3 || mn.length>2 || dt.length>2 || yr.length!=4 || !(parseInt(mn)>=1 && parseInt(mn)<=12) || !(parseInt(yr)>=parseInt(1900) && parseInt(yr)<=parseInt(2100)) || !(parseInt(dt)>=1 && parseInt(dt)<=parseInt(days[parseInt(mn)])) )
{
 invalid = "true";
}
alert( ( invalid=="true" ? "Invalid Date" : "Valid Date")  );
}