Resolved CustomAttribute doesn't work

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:
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!!!!
 
Solution
DataAnnotations Namespace is designed for ASP.Net MVC and data controls meta data, it doesn't do anything with a regular class and property assignment. You can use one of the methods of Validator class to validate on demand.

IsValid returns a bool indicating if object is valid, so you should probably return false instead of throwing exception. This example validates all properties and collects error results, but only if TryValidateObject completes without exception.
C#:
var errorResults = new List<ValidationResult>();
if (Validator.TryValidateObject(user, new ValidationContext(user), errorResults, true))
{
    Console.WriteLine(user.Date);
}
By the way, looks like you have an z too much in the format string.

One more, in...
DataAnnotations Namespace is designed for ASP.Net MVC and data controls meta data, it doesn't do anything with a regular class and property assignment. You can use one of the methods of Validator class to validate on demand.

IsValid returns a bool indicating if object is valid, so you should probably return false instead of throwing exception. This example validates all properties and collects error results, but only if TryValidateObject completes without exception.
C#:
var errorResults = new List<ValidationResult>();
if (Validator.TryValidateObject(user, new ValidationContext(user), errorResults, true))
{
    Console.WriteLine(user.Date);
}
By the way, looks like you have an z too much in the format string.

One more, in TryParseExact call you're not using the parsed date, intellisense suggests to discard it: TryParseExact( ... , out _)
 
Solution

Latest posts

Back
Top Bottom