4.5
(2)

CUSTOM VALIDATION FOR DATE OF BIRTH WITH DATA ANNOTATIONS

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

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

protected override ValidationResult IsValid(object value,ValidationContext validationContext)
        {
            DateTime date;
            bool parsed = DateTime.TryParse((string)value, out date);
            if (!parsed)
                return new ValidationResult("Invalid Date");
            else
            {
                var min = DateTime.Now.AddYears(-18);
                var max = DateTime.Now.AddYears(-100);
                var msg = string.Format("Please enter a value between {0:MM/dd/yyyy} and {1:MM/dd/yyyy}", max, min);
                try
                {
                    if (date > min || date < max)
                        return new ValidationResult(msg);
                    else
                        return ValidationResult.Success;
                }
                catch (Exception e)
                {
                    return new ValidationResult(e.Message);
                }
            }

        }

Here is the complete code.

public class DOBDateValidation : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value,ValidationContext validationContext)
        {
            DateTime date;
            bool parsed = DateTime.TryParse((string)value, out date);
            if (!parsed)
                return new ValidationResult("Invalid Date");
            else
            {
                var min = DateTime.Now.AddYears(-21);
                var max = DateTime.Now.AddYears(-110);
                var msg = string.Format("Please enter a value between {0:MM/dd/yyyy} and {1:MM/dd/yyyy}", max, min);
                try
                {
                    if (date > min || date < max)
                        return new ValidationResult(msg);
                    else
                        return ValidationResult.Success;
                }
                catch (Exception e)
                {
                    return new ValidationResult(e.Message);
                }
            }

        }
    }

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

 [Display(Name = "Date of Birth")]
        [DataType(DataType.Date)]
        [DOBDateValidation]
        [Required]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime DOB { get; set; }

Related: Custom Validation for Date 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?