Created
October 11, 2012 09:09
-
-
Save chrisyip/3871167 to your computer and use it in GitHub Desktop.
A regular expression that validates date.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var re = /^(\d{4})[-\/\.]{0,1}(?:(?:(11|0?[469])[-\/\.]?([12]\d|30|0?[1-9]))|(?:(1[02]|0?[13578])[-\/\.]{0,1}([1-2]\d|3[01]|0?[1-9]))|(?:(0?2)[-\/\.]{0,1}(2[1-9]|1\d|0?[1-9])))$/; | |
// test | |
[ | |
// valid dates | |
'2012-4-21', | |
'2012-04-21', | |
'2012-5-1', | |
'2012-05-31', | |
'2012-11-21', | |
'2012-12-21', | |
'20120412', | |
'20121231', | |
'2012/4/21', | |
'2012/12/21', | |
'2012-2-29', | |
'2012021', // '2012-02-01' | |
'201211', | |
'2012121', | |
'2012131', | |
// invalid dates | |
'2012-2-30', | |
'2012230', | |
'2012.04.32', | |
'2012132', | |
'2012-14-1', | |
'2012-12-32', | |
'2012-13-1', | |
'2012-4-31' | |
].forEach(function(item, idx){ | |
console.log(item) | |
console.log(re.test(item)) | |
// DO NOT forget to call trim() | |
var m = item.trim().match(re) | |
if (m instanceof Array) { | |
console.log(m[0]) | |
console.log(m); | |
} | |
console.log(''); | |
}) | |
// known issue: | |
// #1 | |
// due to regexp implement, the match result will look like this: | |
// [ '2012121', '2012', undefined, undefined, '12', '1', undefined, undefined, index: 0, input: '2012121' ] | |
// the first two `underfined` mean Apr, Jun, Sep and Nov. | |
// the last two `underfined` mean Feb. | |
// #2 | |
// date like '2012121' will always be recognized as '2012-12-1' not '2012-1-21', but '2012131' will be recognized as '2012-1-31' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment