Matt Cowley Matt Cowley - 4 months ago 27
HTML Question

Regex Validation YYYYMMDD

So I need a bit of regex for validation in an input in a form.
I believe you can put regex patterns direct into HTML now? (How do I do this?)

I found this, but I'm not sure whether it is what I want?

"(((\\d\\d)(0[48]|[2468][048]|[13579][26])|([02468][048]|[13579][26])(00))(02)([012]\\d))|(\\d\\d([02468][1235679]|[13579][01345789])(02)([01]\\d|2[012345678]))|(\\d\\d\\d\\d((0[13578]|1[02])([012]\\d|3[01])|((0[46]|11)([012]\\d|30))))"


So, first bit:

4 digits, less than x (2017) (Needs to easily changeable?)

second bit:

2 digits, between 01 and 12

third bit:

2 digits, between 01 and 31 (I don't care for per month changes)

Answer

I believe this should do it:

(201[0-7]|200[0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)

Here's an example on RegExr.

Breakdown:

(201[0-7]|200[0-9]|[0-1][0-9]{3}) matches either:

  • 201 followed by a digit between 0 and 7 (2010..2017)
  • or 200 followed by a digit between 0 and 9 (2000..2009)
  • or a zero or a one, followed by three digits between 0 and 9 (0000..1999). If you do not wish to show years under 1000, you could simply do (201[0-7]|200[0-9]|1[0-9]{3}).

Note: If you wanna match something over 2020, you can change this segment to (202[0-7]|20[01][0-9]|[0-1][0-9]{3}), allowing anything from 0000..2027

The next segment, (1[0-2]|0[1-9]) matches either:

  • a 1 followed by a digit between 0 through 2 (10..12)
  • or a zero followed by a digit between 1 through 9 (01..09)

The last one, (3[01]|[0-2][1-9]|[12]0), matches either:

  • a 3 followed by 0 or 1 (30..31)
  • or a digit between 0 and 2 followed by a digit between 1 and 9 (01..29)
  • or 2 or 1 followed by a 0, since the rule above does not allow the number to end on zero (shutting out 00).
Comments