Reputation: 11375
I currently use the following regex from http://regexlib.com to validate the incoming date using the pattern YYYY-MM-DD. But the leading zeroes are mandatory and I want it to be optional.
((((1[26]|2[048])00)|[12]\d([2468][048]|[13579][26]|0[48]))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|[12]\d))))|((([12]\d([02468][1235679]|[13579][01345789]))|((1[1345789]|2[1235679])00))-((((0[13578]|1[02])-(0[1-9]|[12]\d|3[01]))|((0[469]|11)-(0[1-9]|[12]\d|30)))|(02-(0[1-9]|1\d|2[0-8]))))
2000-01-01
2000-1-1
2000-01-1
2000-1-01
are all valid. But only the first test case is accepted, as of now.
Can you please help?
Upvotes: 0
Views: 1918
Reputation: 147523
You can achieve this much more simply using a function rather than a regular expression. The following is much simpler to understand and therefore maintain (though it shouldn't ever need any), and is a lot less code that the regular expression in the OP.
function isValidISODate(s) {
var b = s.split(/\D/);
var d = new Date(b[0],--b[1],b[2]);
return d && d.getMonth() == b[1];
}
// Some tests
['2016-1-1','2016-01-01','2016-2-29','2016-02-30'].forEach(
s=>console.log(s + ': ' + isValidISODate(s))
);
Upvotes: 1
Reputation: 32807
You can make a number optional by adding them the number of permitted ocurrences {0,1}
. That is {1,2}
to accept either 1 character or 2.
A simple version:
[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}
Edit: Your version is easy to "fix". Simply add {0,1}
after the compulsory 0:
// Before.
((((0[13578]
// After.
((((0{0,1}[13578]
Edit2: As @Toto has said {0,1}
is the same as ?
((((0?[13578]
Upvotes: 0