0

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]))))

Regular expression visualization

Debuggex Demo

Test case

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?

Srini V
  • 11,045
  • 14
  • 66
  • 89
  • Just use a simple regex - `\d{4}-\d{1,2}-\d{1,2}` – Philipp Jan 16 '17 at 10:42
  • Don't use a regular expression at all, see [*How to validate a date?*](http://stackoverflow.com/questions/5812220/how-to-validate-a-date/5812341#5812341). – RobG Jan 16 '17 at 11:01

3 Answers3

1

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))
);
RobG
  • 142,382
  • 31
  • 172
  • 209
0

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]
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • 2
    I think this is a more complex Regex designed to not only check the YYYY-MM-DD format but to actually check that it is a legitimate date. – EDD Jan 16 '17 at 10:27
  • @Someone edited to reflect the result with his version – zurfyx Jan 16 '17 at 10:33
0

Using this regex - '\d+-[0-2]* [0-9]-[0-3]* [0-9]' may help .

hvaminion
  • 135
  • 3
  • 10