Custom Validation for Start Date with Data Annotations C# (ASP.NET MVC)

5
(6)

Custom Validation for Start Date with Data Annotations C# (ASP.NET MVC)

Here is the code to check whether the Start date is valid or not means the start date needs to compare with the current date and it should not the backdate using custom validation with Data Annotations using C# (ASP.Net MVC)

You can also consider this example as Back Date Validation Using Data Annotation C# (ASP.NET MVC)

Step 1: Create a new class with the name StartDateAttribute 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 StartDateAttribute

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime _dateStart = Convert.ToDateTime(value);
            if (_dateStart >= DateTime.Now)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(ErrorMessage);
            }
        }

Here is the complete code.

public class StartDateAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime _dateStart = Convert.ToDateTime(value);
            if (_dateStart >= DateTime.Now)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(ErrorMessage);
            }
        }
    }

Step 3: Use our custom start date validator in the Model.

[Required]
        [Display(Name = "Start Date")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [StartDate(ErrorMessage = "Back date entry not allowed")]
        public DateTime startDate { get; set; }

Related: Custom Validation for Date with Data Annotations | Custom Validation for Date of Birth with Data Annotations

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 6

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?