One more regular expression

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

How can I write a regular expression that have a pattern for a YYYY-MM-DD
that must satisfy the following.
1. Must not be a date in future relative today date.
2.Can at most be a date that is 3 month back in time relativer today date

//Tony
 
How can I write a regular expression that have a pattern for a
YYYY-MM-DD that must satisfy the following.
1. Must not be a date in future relative today date.
2.Can at most be a date that is 3 month back in time relativer today date

Regex is not the right toll for this task.

DateTime.TryParseExact followed by a test on interval must
be the right way to do that.

Arne
 
Regex is not the right toll for this task.

DateTime.TryParseExact followed by a test on interval must
be the right way to do that.

For inspiration:

public static bool IsValidDate(string s)
{
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd", new
CultureInfo("en-US"), DateTimeStyles.None, out dt))
{
if(dt > DateTime.Now.Date || dt <
DateTime.Now.AddMonths(-3))
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}

Arne
 
For inspiration:

public static bool IsValidDate(string s)
{
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd", new
CultureInfo("en-US"), DateTimeStyles.None, out dt))
{
if(dt > DateTime.Now.Date || dt <
DateTime.Now.AddMonths(-3))
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}

Note that this type of test is somewhat questionable
in design.

Whether input is in the correct format and specify
a date that exist belongs in the presentation layer.

But whether it is in the past 3 months most likely
belongs in the business logic layer.

Arne
 
Tony said:
How can I write a regular expression that have a pattern for a
YYYY-MM-DD that must satisfy the following.
1. Must not be a date in future relative today date.
2.Can at most be a date that is 3 month back in time relativer today date

Hello,

I think it must be a valid date, the 31th day of november will be
invalid. Checking for a valid date is much to complicated with regular
expressions.

You better use DateTime.TryParseExact as already suggested.

Bye
 
Back
Top