Dragon4ik
Member
- Joined
- Oct 24, 2020
- Messages
- 16
- Programming Experience
- Beginner
Hi, everybody!
I try to create attribute, which would validate a string format for parsing into DateTimeOffset.
Here is DateStringAttribute code:
Model Code:
and Main():
If attribute worked, it would thrown exception, but it doesn't and I can't understand WHY?
Thank you for any help!!!!
I try to create attribute, which would validate a string format for parsing into DateTimeOffset.
Here is DateStringAttribute code:
C#:
public class DateStringAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
string date = value.ToString();
var format = "ddd MMM dd yyyy HH:mm:ss 'GMT'zzzz";
IFormatProvider provider = CultureInfo.InvariantCulture.DateTimeFormat;
DateTimeOffset startDate;
if (!DateTimeOffset.TryParseExact(date, format, provider, DateTimeStyles.AllowWhiteSpaces, out startDate))
{
throw new Exception("Something went wrong");
}
return true;
}
}
Model Code:
C#:
public class User
{
[DateString]
public string Date { get; set; }
}
and Main():
C#:
public static void Main()
{
try
{
User user = new User { Date = "Fri Aug 30 2014 00:00:00 GMT+0300" };
Console.WriteLine(user.Date);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
If attribute worked, it would thrown exception, but it doesn't and I can't understand WHY?
Thank you for any help!!!!