How do I implement custom model validation in ASP.NET Core?

孤人 提交于 2020-01-24 02:00:07

问题


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. As an example:

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:


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.



来源:https://stackoverflow.com/questions/38332712/how-do-i-implement-custom-model-validation-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!