0

I am using data annotations with MVC2 to validate a date of birth. The date of birth has 3 different fields. (Month, Day and Year) (they have to be three individual fields)

Right now I have individual data annotations for each field. How can I make it so that all three fields are validated and show one error message in my view. The setup I have right now creates an error message for each field.

If any one of those fields throws an error, I want to show a generic error message like "Date of Birth invalid".

Month Field:

        [Required]
        [DisplayName("Month")]
        public IEnumerable<string> Months 
        { 
            get 
            {
                if (_Months == null)
                {
                    List<string> months = new List<string>();
                    months.Add("-- Select Month --");
                    months.AddRange(DateTimeFormatInfo.CurrentInfo.MonthNames.Select(Month => Month).ToList());
                    months.RemoveAt(months.Count - 1);
                    _Months = months;
                }
                return _Months;
            }
            set { _Months = value; }
        }

        private IEnumerable<string> _Months;

        public string SelectedMonth {get; set;}

Day Field:

    [Required]
    [DisplayName("Day")]
    [Range(1,31, ErrorMessage = "Not a valid day")]
    public int? Day { get; set; }

Year Field:

    [Required]
    [DisplayName("Year")]
    [Range(1900,9999, ErrorMessage = "Not a valid year")]
    [ValidateBirthYear]
    public int? Year { get; set; } 
Farhan Ahmad
  • 5,148
  • 6
  • 40
  • 69

1 Answers1

0

You might want to check out this question. They are looking to validate a datetime that is separated into three fields as well.

Community
  • 1
  • 1
Jared
  • 2,736
  • 1
  • 18
  • 23