0

I am using Single line Text field where user is entering date. How to perform check if value entered is in mm/dd/yyyy format using Sitecore Regex Validation. It should also consider leap year validation. Like, if 30/02/2023 is entered then it should be invalid date.

Any suggestion ?

1

2 Answers 2

0
^(0[1-9]|1[0-2])/(0[1-9]|1\d|2[0-8])/(19\d{2}|20\d{2})|(0[13-9]|1[0-2])/(29|30)/(19\d{2}|20\d{2})|(0[13578]|1[02])/31/(19\d{2}|20\d{2})|(0[1-9]|1[0-2])/29/((19(([2468][048])|([13579][26]))|([2468][048])|([13579][26]))|(20(([2468][048])|([13579][26]))|([2468][048])|([13579][26]))))$

This regex pattern checks for dates in the mm/dd/yyyy format and also takes leap years into account. Here's a breakdown of the regex:

(0[1-9]|1[0-2]): Matches months from 01 to 12.
(0[1-9]|1\d|2[0-8]): Matches days from 01 to 28.
(19\d{2}|20\d{2}): Matches years in the range 1900 to 2099.
(0[13-9]|1[0-2])/(29|30)/(19\d{2}|20\d{2}): Matches months with 29 or 30 days and validates leap years.
(0[13578]|1[02])/31/(19\d{2}|20\d{2}): Matches months with 31 days.
Leap year validation: It checks for leap years by considering both divisible by 4 (except for years divisible by 100 but not by 400) and not divisible by 100 but divisible by 4.

Note: I have not tested this on my instance.

2
  • THis is not working.
    – Gagan
    Sep 13, 2023 at 14:57
  • @Gagan Could you please test this in segments? For example, start by testing only the "(0[1-9]|1[0-2])" part and then proceed with the rest.
    – Gautam
    Sep 13, 2023 at 15:11
0

Creating a regex to validate a date, including leap year consideration, can be quite complex due to the variety of rules surrounding date validation. For instance, you need to ensure the month entered is between 01 and 12, the day is valid for the given month, and the year is a valid 4-digit number. Additionally, leap year validation requires checking if February has 29 days in a leap year and 28 days otherwise.

A regex pattern for this validation in a Sitecore Form might look something like the pattern below. This pattern checks the format and the validity of the date, including the leap year consideration for February:

^(?:(?:(?:0[1-9]|1[0-2])/(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])/(?:29|30)|(?:0[13578]|1[02])/31)/(?:19|[2-9]\d)\d{2}|02/(?:29)/(?:19|[2-9]\d)(?:(?:00)|(?:\d\d(?:[02468][1235679]|[13579][01345789]))))$

Explanation:

  1. The regex is broken down into three main parts, one for each month length (28/29, 30, or 31 days).
  2. It checks the month, day, and year ranges and formats, and includes a special case for leap years in February.
  3. Leap years are identified as years divisible by 4, except for end-of-century years, which must be divisible by 400.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.