1
Question Body:

I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET

Edit
avatar
asked15 years ago

    Leave a Comment

    [named hyperlinks] (https://example.com)
    **bold**
    _italic_

    5 Answer

    0

    I don't think this is a task very well-suited for a regexp.

    I'd try and use the library functions (DateTime.Parse for .NET) to parse the date and then check the day component of it. Everything else is duplicating half the library function anyways.

    Edit
    avatar
    answered15 years ago
    0

    Why not just covert it to a date data type and check the day? Using a regular expression, while it could be done, just makes it overly complicated.

    Edit
    avatar
    answered15 years ago
    0

    Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead:

    DateTime parsedDate;
    
    if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )
    {
     // logic goes here.
    }
    

    Regex is nearly the golden hammer of input validation, but in this instance, it's the wrong choice.

    Edit
    avatar
    answered15 years ago
    0
      ([1-9]|1\d|2[0-8]) // matches 1 to 28 but woudn't allow leading zeros for single digits
    (0?[1-9]|1\d|2[0-8]) // matches 1 to 28 and would allow 01, 02,... 09
    

    (where \d matches any digit, use [0-9] if your regex engine doesn't support it.)

    See also the question What is the regex pattern for datetime (2008-09-01 12:35:45 ) ?

    Edit
    avatar
    answered15 years ago
    0

    I would use one of the DateTime.TryParse techniques in conjunction with a CustomValidator

    Edit
    avatar
    answered15 years ago

    Your Answer

    Drop files here or click to upload.
    undraw-questions

    Disilab for your Teams

    – Collaborate and share knowledge with a private group.

    Create a free Team