'Regex for DateTimeOffset validation in url?
How to validate the date and time in the url that is the correct DateTimeOffset format?
DateTimeOffset format (basically starts with 4 digits of year and end with uppercase Z):
- yyyy-mm-ddZ
- yyyy-mm-ddThh:mm:ssZ
- yyyy-mm-ddThh:mm:ss.fffffZ
Valid DateTimeOffset in the url:
- aaa.com/activityDateTime eq 2022-05-12Z
- aaa.com/activityDateTime eq 2022-05-12T12:00:00Z
- aaa.com/activityDateTime%20eq%202022-05-12T12:00:00Z
- aaa.com/activityDateTime+eq+2022-05-12T12:00:00.123456Z
- aaa.com/activityDateTime gt 2022-03-12Z le 2022-05-12Z
Note: eq means equal, gt means greater than, le means less than
Invalid DateTimeOffset in the url:
- aaa.com/activityDateTime eq 2022-05-12
- aaa.com/activityDateTime eq 2022-05-12T12:00:00
- aaa.com/activityDateTime%20eq%202022-05-12T12:00:00
- aaa.com/activityDateTime+eq+2022-05-12T12:00:00.123456
I'm currently convert the url to string and use Regex to validate it, but not sure what's the proper way to handle the case where url contains "%20". Is there a way not to use Replace()? Also, any other suggestions to validate DateTimeOffset in the url? Here's my current regex expression:
Regex checkDate = new Regex(@"^(?!\d{4}-\d{2}-\d{2}Z)");
Regex checkDateTime = new Regex(@"^(?!\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)");
Solution 1:[1]
If you need a regex to validate DateTimeOffset, you can use the following one:
^[A-Za-z\.\/]+( |%20|\+)(eq|gt)( |%20|\+)[\d\-]+(T[\d:]+(\.[\d]+)?Z|Z( [a-z]+ [\d\-]+Z)?)$
Explanation:
^
: start string[A-Za-z\.\/]+
: any combination of alphabetic character, dots and slashes( |%20|\+)
: single space or %20 or +(eq|gt)
: eq or gt( |%20|\+)
: single space or %20 or +[\d\-]+
: any combination of digits and dashes (the date)
The last part (T[\d:]+(\.[\d]+)?Z|Z( [a-z]+ [\d\-]+Z)?)
can match one between two different suffixes.
Suffix 1 T[\d:]+(\.[\d]+)?Z
:
T
: T[\d:]+
: any combination of digits and : (the time)(\.[\d]+)?
: optional presence of single dot with a combination of digits (milliseconds?)Z
: Z
Suffix 2 Z( [a-z]+ [\d\-]+Z)?
:
Z
: Z( [a-z]+ [\d\-]+Z)?
: optional presence of a space, followed by letters, a space, combination of digits and dashes (a date), a Z
The whole regex is wrapped up with:
$
: end of string
If instead you want to match only the DateTimeOffset, use only the following part of this regex:
[\d\-]+(T[\d:]+(\.[\d]+)?Z|Z( [a-z]+ [\d\-]+Z)?)$
Test this regex here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lemon |