validate age according to date of birth using model in mvc 4

后端 未结 4 1422
闹比i
闹比i 2020-12-10 09:17

I have registration form and its contain date of birth field.

Using calender date picker its input the value to this field.

these are the steps to insert

4条回答
  •  伪装坚强ぢ
    2020-12-10 09:50

    Well since you are already using data annotations why not make your own. do this:

    create a class in an dll that you use or make a new one and at a minimum add the following code to it

    public class MinimumAgeAttribute: ValidationAttribute
    {
        int _minimumAge;
    
        public MinimumAgeAttribute(int minimumAge)
        {
          _minimumAge = minimumAge;
        }
    
        public override bool IsValid(object value)
        {
            DateTime date;
            if (DateTime.TryParse(value.ToString(),out date))
            {
                return date.AddYears(_minimumAge) < DateTime.Now;
            }
    
            return false;
        }
    }
    

    then in your view model do this:

    [MinimumAge(18)]
    [DisplayName("Date of Birth")]
    [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public Nullable Date_of_Birth { get; set; }
    

    or your web page you will have no issues as the framework(s) you use will pick it up. Without changing the ErrorMessage property in your class you will get something like

    The field "{0}" is not valid.

    The {0} is replaced by the property name or display name attribute that you gave the property in your model.

    Hope it works for you.

    Walter ps: make sure in the controller you do

    if (ModelState.IsValid)
    {
     ....
    }
    

提交回复
热议问题