ASP.NET DataAnnotations正则:如何匹配1-53周数的年周格式?
Fixing the Work Week Validation Regex for ASP.NET ViewModels
Got it, let's get that regex sorted to meet all your validation needs. Your original pattern works for most cases but misses two key requirements: supporting 1-digit week numbers (like 2010-1) and blocking invalid week values (00, 54+, etc.).
First, Let's Define the Exact Rules We Need to Match
- Year: Exactly 4 digits (your examples include
6502so we don't need to restrict the year range) - Separator: A single hyphen
- - Week Number: Must be between 1-53, supporting:
- 1-digit format:
1to9 - 2-digit format:
01to09(with leading zero) and10to53
- 1-digit format:
- Invalid Cases to Block:
00,54to99
The Corrected Regular Expression
Here's the regex that covers all these rules:
^\d{4}-(?:0?[1-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-3])$
Breaking Down the Pattern
Let's walk through each part to make it clear:
^: Start-of-string anchor (ensures we don't match partial values likeabc2024-12)\d{4}: Matches exactly 4 digits for the year-: Literal hyphen separator(?:...): Non-capturing group (groups our week number options without creating unnecessary capture groups)0?[1-9]: Matches 1-9, with an optional leading zero (so1,01,9,09all work)|: OR operator, separating valid week number ranges1[0-9]: Matches 10-192[0-9]: Matches 20-293[0-9]: Matches 30-394[0-9]: Matches 40-495[0-3]: Matches 50-53 (blocks 54 and above)
$: End-of-string anchor (ensures no extra characters after the week number, like2024-12x)
Implementing in ASP.NET ViewModel
Drop this into your RegularExpression attribute, with a clear error message:
[RegularExpression(@"^\d{4}-(?:0?[1-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-3])$", ErrorMessage = "Work Week must follow the format XXXX-WW where XXXX is a 4-digit year, and WW is a week number between 1-53 (supports 1-digit like 2010-1 or 2-digit like 2019-09)")] public string WorkWeek { get; set; }
Validating Your Test Cases
Let's confirm this works with your examples:
- Valid matches:
2001-01,2001-10,2010-1,6502-9→ all are accepted - Invalid matches:
2056-54,2068-60,5416-00→ all are rejected (as expected)
Why Your Original Regex Failed
Your original pattern [\d]{4}-[0-5]\d had two key issues:
- It required the week number to be exactly two digits, so 1-digit values like
2010-1were rejected - It allowed invalid week numbers:
00(since[0-5]\dmatches00) and54-59(since[0-5]allows 5 as the first digit, followed by any digit)
内容的提问来源于stack exchange,提问作者Luke Hammer
相关产品推荐
相关产品推荐

