One more regular expression

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
 
A

Arne Vajhøj

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
 
A

Arne Vajhøj

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
 
A

Arne Vajhøj

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
 
U

Uwe Hercksen

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top