简体   繁体   中英

javascript date validation (length 2 digit month, day, 4 digit year)

Here is the date validation I am currently using, it works, but I want to make sure 2 digits are entered for month and 2 for Day. I am not too familiar with javascript, and getting this far took lots of searching on here. Any help would be appreciated. Thanks

 function validate_birthday(field,alerttxt)
 {  
 with (field)
 {
 dateParts = value.split('-');
 if(dateParts.length != 3) {
 alert('Date Format Must Be MM-DD-YYYY');
 return false; }
  testDate = new Date(dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0]);  

if(isNaN(testDate.getDate())) {     alert('Date Format Must Be MM-DD-YYYY');     return false; 

 } 
 else {return true;}
}
}

Try using a regular expression instead to match on the date format.

/[0-1]{1}[0-9]{1}-[0-3]{1}[0-9]{1}-2[0-9]{3}/

or a simpler way simply checking for 2 numbers a hyphen 2 numbers a hyphen and 4 numbers:

/[0-9]{2}-[0-9]{2}-[0-9]{4}/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM