Monday 28 November 2011

How to Create Custom Date Validation for MVC3

Suppose you want to ensure that a Date is not in the future.

You need to add a Custom Data Annotation - by inheriting from ValidationAttribute class.

    public class DateNotInFutureAttribute : ValidationAttribute
    {
        public DateNotInFutureAttribute()
            : base(_defaultError)
        {

        }

        private const string _defaultError = "{0} cannot be in the future";

        public override bool IsValid(object value)
        {
            DateTime val = (DateTime)value;
            return DateTime.Now.Ticks < val.Ticks ? false : true;
        }
    }


Then in your Model you simply add your new attribute:

        [DataType(DataType.Date)]
        [DisplayName("Date Revised")]
        [DateNotInFuture]
        public object DATE_REVISED { get; set; }

No comments:

Post a Comment