Credit Cards

Validate the Expiration Date of a Credit Card

I needed an attribute to validate the credit card expiration date and couldn’t find any good examples. I have it working now, so others can use it.

Here is the action that does the validation:

    class ExpirationDateAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return Convert.ToDateTime(value).Date >= DateTime.Today.AddDays(DateTime.Today.Day * -1 + 1).Date;
        }
    }

In your form model, do the following:

        [Required(ErrorMessage = "Please enter your expiration month.")]
        public int ExpireMonth { get; set; }
        [Required(ErrorMessage = "Please enter your expiration year.")]
        public int ExpireYear { get; set; }
        [ExpirationDate(ErrorMessage="Expiration Date cannot be in the past.")]
        public string ExpirationDate { get { return new DateTime(ExpireYear, ExpireMonth, 1).ToString("MM/yyyy"); }}