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

后端 未结 4 1435
闹比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:58

    I've improved on Walter's answer regarding making your own custom validation. I've added better error message support. This will allow a better default error message and also allow you to enter your own with better string.Format support. I've also updated the naming schemes. For instance you should add date to the beginning so that you and other developers know that this validation can only be used with DateTime variables similar to how the base StringLengthAttribute is named for strings.

    public class DateMinimumAgeAttribute : ValidationAttribute
    {
        public DateMinimumAgeAttribute(int minimumAge)
        {
            MinimumAge = minimumAge;
            ErrorMessage = "{0} must be someone at least {1} years of age";
        }
    
        public override bool IsValid(object value)
        {
            DateTime date;
            if ((value != null && DateTime.TryParse(value.ToString(), out date)))
            {
                return date.AddYears(MinimumAge) < DateTime.Now;
            }
    
            return false;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessageString, name, MinimumAge);
        }
    
        public int MinimumAge { get; }
    }
    
    
    [DateMinimumAge(18, ErrorMessage="{0} must be someone at least {1} years of age")]
    [DisplayName("Date of Birth")]
    [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public Nullable Date_of_Birth { get; set; }
    

提交回复
热议问题