Custom Validation for Date with Data Annotations

CUSTOM VALIDATION FOR DATE WITH DATA ANNOTATIONS

Here is the code to check whether date is valid or not using custom validation with Data Annotations using C# (ASP.Net MVC)

Step 1: Create a new class with the name DateValidation and inherit ValidationAttribute. ValidationAttribute required System.ComponentModel.DataAnnotations namespace so we need to add “using System.ComponentModel.DataAnnotations;” at the top.


Step 2: Add the following code within the class DateValidation

public override bool IsValid(object value)
        {
            DateTime dt;
            bool parsed = DateTime.TryParse(value.ToString(), out dt);
            if (!parsed)
                return false;
            //  business logic here
            return true;
        }

Here is the complete code.

 public class DateValidation : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime dt;
            bool parsed = DateTime.TryParse(value.ToString(), out dt);
            if (!parsed)
                return false;
	    //  business logic here
            return true;
        }
    }

Step 3: Use our custom date validator in the Model

	[Display(Name = "Joining Date")]
        [DataType(DataType.Date)]
        [DateValidation(ErrorMessage = "Invalid Date")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime JoiningDate { get; set; }

Related: Custom Validation for Date of Birth with Data Annotations