Custom Validation for Date with Data Annotations

4.5
(2)

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

How useful was this post?

Click on a star to rate it!

Average rating 4.5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?