Friday, June 9, 2023

ASP.NET Core MVC model class Property Validation


There are two approaches to validate properties in ASP.NET MVC Core. First approach is to validate a single property of a class but we can also validate all the properties of the class in one go. 


Single Propery Validation

Create a class which inherits from ValidationAttribute class. The ValidationAttribute class contains the IsValid method which is overridden in the derived class. The IsValid method returns an object of the ValidationResult.


using System;
using System.ComponentModel.DataAnnotations;

namespace HelloMVCWorld.Helpers
{
    public class BirthdayValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime birthday = (DateTime)value;

            if (birthday.Year < 1900)

                return new ValidationResult("Can't be too old");

            if (birthday.Year > 2000)

                return new ValidationResult("Sorry, you're too young!");

            if (birthday.Month == 11)

                return new ValidationResult("Sorry, we don't accept anyone born in November!");

            return ValidationResult.Success;
        }
    }
}

No comments:

Post a Comment

Hot Topics