@@ -17,12 +17,7 @@ function isDate(value: string): boolean {
1717 if ( value . trim ( ) . length === 0 ) {
1818 throw new Error ( "Input value must not be an empty string." ) ;
1919 }
20- // Parse the value using the Date constructor
21- const dateObject : Date = new Date ( value ) ;
22- // Check if the parsed date is valid
23- if ( Number . isNaN ( dateObject ) || ! ( dateObject instanceof Date ) ) {
24- return false ;
25- }
20+
2621 // Check if the date string is in a valid format (e.g., 'YYYY-MM-DD', 'MM/DD/YYYY', 'MMMM D, YYYY')
2722 const dateStringRegex1 : RegExp = / ^ \d { 4 } [ - / ] \d { 2 } [ - / ] \d { 2 } $ / ; // 'YYYY-MM-DD' or 'YYYY/MM/DD'
2823 const dateStringRegex2 : RegExp = / ^ \d { 2 } [ - / ] \d { 2 } [ - / ] \d { 4 } $ / ; // 'MM-DD-YYYY' or 'MM/DD/YYYY'
@@ -34,10 +29,29 @@ function isDate(value: string): boolean {
3429 ) {
3530 return false ;
3631 }
37- // Additional checks for the month and day values
38- const year : number = dateObject . getFullYear ( ) ;
39- const month : number = dateObject . getMonth ( ) + 1 ; // Month is zero-based, so we add 1
40- const day : number = dateObject . getDate ( ) ;
32+
33+ let year : number , month : number , day : number ;
34+
35+ if ( dateStringRegex1 . test ( value ) ) {
36+ // 'YYYY-MM-DD' or 'YYYY/MM/DD'
37+ const parts : string [ ] = value . split ( / [ - / ] / ) ;
38+ year = parseInt ( parts [ 0 ] , 10 ) ;
39+ month = parseInt ( parts [ 1 ] , 10 ) ;
40+ day = parseInt ( parts [ 2 ] , 10 ) ;
41+ } else if ( dateStringRegex2 . test ( value ) ) {
42+ // 'MM-DD-YYYY' or 'MM/DD/YYYY'
43+ const parts : string [ ] = value . split ( / [ - / ] / ) ;
44+ month = parseInt ( parts [ 0 ] , 10 ) ;
45+ day = parseInt ( parts [ 1 ] , 10 ) ;
46+ year = parseInt ( parts [ 2 ] , 10 ) ;
47+ } else {
48+ // 'MMMM D, YYYY'
49+ const parts : string [ ] = value . split ( / [ \s , ] + / ) ;
50+ month = new Date ( Date . parse ( parts [ 0 ] + " 1, 2000" ) ) . getMonth ( ) + 1 ;
51+ day = parseInt ( parts [ 1 ] , 10 ) ;
52+ year = parseInt ( parts [ 2 ] , 10 ) ;
53+ }
54+
4155 if (
4256 year < 1000 ||
4357 year > 9999 ||
@@ -48,6 +62,25 @@ function isDate(value: string): boolean {
4862 ) {
4963 return false ;
5064 }
65+
66+ // Check if the day is valid for the given month and year
67+ const daysInMonth : number [ ] = [
68+ 31 ,
69+ ( year % 4 === 0 && year % 100 !== 0 ) || year % 400 === 0 ? 29 : 28 ,
70+ 31 ,
71+ 30 ,
72+ 31 ,
73+ 30 ,
74+ 31 ,
75+ 31 ,
76+ 30 ,
77+ 31 ,
78+ 30 ,
79+ 31 ,
80+ ] ;
81+ if ( day > daysInMonth [ month - 1 ] ) {
82+ return false ;
83+ }
5184 return true ;
5285}
5386export default isDate ;
0 commit comments