42

In previous versions of ASP.NET MVC the way to add custom validation to your model was by implementing the IValidatableObject and implementing your own Validate() method.

Here's what I have implemented:

public class BestModelEver: IValidatableObject 
{
    public DateTime? Birthday { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    {
        if (Birthday.HasValue) 
        {
          yield return new ValidationResult("Error message goes here");
        }
    }
}

Is this still the recommended way of adding custom validation to a model in ASP.NET Core? Using IValidatableObject takes on a System.ComponentModel.DataAnnotations dependency.

1 Answer 1

42

There are two ways to do custom model validation in ASP.NET Core:

  • A custom attribute subclassed from ValidationAttribute. This is useful when you want to apply custom business logic to a particular model property with an attribute.
  • Implementing IValidatableObject for class-level validation. Use this instead when you need to do validation on an entire model at once.

The documentation has examples of both. In your case, IValidatableObject would probably be the best approach.

Sign up to request clarification or add additional context in comments.

1 Comment

I was looking for a custom validation section in their docs, but it looks like I missed it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.