ASP.net MVC Validation on mutiple controls
I have a strongly typed view which is bound to a ViewModel, one prupose of which is to capture the customers date of birth. To do this I have a number of fields within the ViewModel, defined as follows:
public DateTime DOB {get;set;}
public int? DOBDay
{
get
{
return _DOBDay;
}
set
{
_DOBDay = value;
SetDOB();
}
}
public int? DOBMonth
{
get
{
return _DOBMonth;
}
set
{
_DOBMonth = value;
SetDOB()开发者_如何学JAVA;
}
}
public int? DOBYear
{
get
{
return _DOBYear;
}
set
{
_DOBYear = value;
SetDOB();
}
}
public List<SelectListItem> DOBDayItems { get; set; }
public List<SelectListItem> DOBMonthItems { get; set; }
public List<SelectListItem> DOBYearItems { get; set; }
protected void SetDOB()
{
if (this.DOBDay.HasValue && this.DOBMonth.HasValue && this.DOBYear.HasValue)
{
DateTime dob = new DateTime(this.DOBYear.Value, this.DOBMonth.Value, this.DOBDay.Value);
//Check within smalldatetime range
if (dob < new DateTime(2079, 6, 6) && dob > new DateTime(1900, 1, 1))
{
this.DOB = dob;
}
}
}
This then facilitates 3 dropdowns on my form, bound to DOBDay, DOBMonth and DOBYear respectively (n.b. this has proven to be the easiest method of entering a date of birth in a number of user experience testing experiments we have carried out). The DOB is then set whenever any of these is changed which works fine.
I am using DataAnnotations to validate the form which works fine for validating each one of the 3 dropdowns (required / max values) however there is the additional validation needed to ensure that DOB is a valid date - 30 Feb 1985 would pass the individual dropdown validation however is not valid. I would like this to highlight all 3 controls, but potentially only be fired by the DOBYear drop down but am not sure how to go about this - is it possible?
精彩评论