Is DateTime

Check if the datetime entered can be converted to a C# DateTime.


using System;
using System.Globalization;
using System.ComponentModel.DataAnnotations;

namespace Your.Namespace
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed public class IsDateTime : ValidationAttribute
    {
        private DateTime _dateTime;
        private readonly string _format;
        private readonly bool _parseExact;

        /// 
        /// Checks if the value is in DateTime Format.
        /// 
        ///Only used if you need an exact datetime format to be parsed. Ex: "yyyy-dd-MM hh:mm tt"
        public IsDateTime(string format = "")
        {
            _format = format;
            _parseExact = !string.IsNullOrEmpty(format);
        }

        public override bool IsValid(object value)
        {
            if (value != null)
            {
                if (_parseExact)
                {
                    if (!DateTime.TryParseExact(value.ToString(), _format, CultureInfo.InvariantCulture, DateTimeStyles.None, out _dateTime))
                    {
                        return false;
                    }
                }
                else
                {
                    if (!DateTime.TryParse(value.ToString(), out _dateTime))
                    {
                        return false;
                    }
                }

            }
            return true;
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
        }
    }
}

Exsample of how to use it.


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Your.Namespace
{
    public class YourModel
    {
        // Specific format required.
        [IsDateTime(format: "yyyy-dd-MM hh:mm tt", ErrorMessage = "Wrong Datetime")]
        public string Date { get; set; }

        // Any format as long as it can be converted into a datetime.
        [IsDateTime(ErrorMessage = "Wrong Datetime")]
        public string AnotherDate { get; set; }
    }
}