1.5.2.Data annotation

  • 1.Add new class inherit ValidationAttribute

    public class Min18YearsIfAMember: ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var customer = (Customer)validationContext.ObjectInstance;
            if (customer.membershipTypeId == 1)
            {
                return ValidationResult.Success;
            }
            if (customer.Birthday == null)
            {
                return new ValidationResult("Birthdate is required");
            }
            return ValidationResult.Success;
        }
    }
  • 2.Add data annotation to the model

        [Display(Name = "Date or Birth")]
        [Min18YearsIfAMember]
        public string Birthday { get; set; }
  • 3.Add warning message to the view

    <div class = "form-group">
        @Html.LabelFor(m => m.customer.Name)
        @Html.TextBoxFor(m => m.customer.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.customer.Name);
    </div>

Last updated