You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 6502 so we don't need to restrict the year range)
  • Separator: A single hyphen -
  • Week Number: Must be between 1-53, supporting:
    • 1-digit format: 1 to 9
    • 2-digit format: 01 to 09 (with leading zero) and 10 to 53
  • Invalid Cases to Block: 00, 54 to 99

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 like abc2024-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 (so 1, 01, 9, 09 all work)
    • | : OR operator, separating valid week number ranges
    • 1[0-9] : Matches 10-19
    • 2[0-9] : Matches 20-29
    • 3[0-9] : Matches 30-39
    • 4[0-9] : Matches 40-49
    • 5[0-3] : Matches 50-53 (blocks 54 and above)
  • $ : End-of-string anchor (ensures no extra characters after the week number, like 2024-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:

  1. It required the week number to be exactly two digits, so 1-digit values like 2010-1 were rejected
  2. It allowed invalid week numbers: 00 (since [0-5]\d matches 00) and 54-59 (since [0-5] allows 5 as the first digit, followed by any digit)

内容的提问来源于stack exchange,提问作者Luke Hammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:22:50