regexdatevalidationparsingmap-force

Regex to validate date format


I'm figuring out a way to validate my input date in Altva Mapforce which is in the format "YYYYMMDD".

I know to verify year I can use [0-9]{4} but I'm having trouble figuring out a way to "restrict" date range to "01-31" and month to "01-12". Please note "01" is valid while "1" should be invalid.

Can someone please provide a regex expression to validate this sort of input?

From searching internet I got one for month: ([1-9]|[12]\d|3[01]) but this one is valid for range 1-31. I want 01-31 and so on.


Solution

  • For a month from 1-12 adding a zero for a single digit 1-9:

    (?:0[1-9]|1[012])
    

    For a day 1-31 adding a zero for a single digit 1-9:

    (?:0[1-9]|[12]\d|3[01])
    

    Putting it all together with 4 digits to match a year (note that \d{4} can also match 0000 and 9999), enclosed in word boundaries \b to prevent a partial match with leading or trailing digits / word characters:

    \b\d{4}(?:0[1-9]|1[012])(?:0[1-9]|[12]\d|3[01])\b
    

    A variation, limiting the scope for a year to for example 1900 - 2099

    \b(?:19|20)\d{2}(?:0[1-9]|1[012])(?:0[1-9]|[12]\d|3[01])\b
    

    But note that this does not validate the date itself, it can for example also match 20210231. To validate a date, use a designated api for handling a date in the tool or code.