ASP.net MVC Validation on mutiple controls

谁说我不能喝 提交于 2019-12-08 08:47:06

问题


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();
        }
    }
    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?

来源:https://stackoverflow.com/questions/5620340/asp-net-mvc-validation-on-mutiple-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!