如何在ASP.NET Core中实现自定义模型验证?

编程入门 行业动态 更新时间:2024-10-10 10:26:57
本文介绍了如何在ASP.NET Core中实现自定义模型验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在ASP.NET MVC的早期版本中,向模型添加自定义验证的方法是实现IValidatableObject并实现自己的Validate()方法.例如:

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"); } } }

这仍然是向ASP.NET Core中的模型添加自定义验证的推荐方法吗?使用IValidatableObject具有System.ComponentModel.DataAnnotations依赖性.

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.

推荐答案

在ASP.NET Core中有两种方法可以进行自定义模型验证:

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

  • 从ValidationAttribute子类化的自定义属性.当您要将自定义业务逻辑应用于具有属性的特定模型属性时,这很有用.
  • 实施IValidatableObject进行类级验证.如果您需要一次对整个模型进行验证,请改用此方法.
  • 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.

文档都有这两个例子.在您的情况下,IValidatableObject可能是最好的方法.

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

更多推荐

如何在ASP.NET Core中实现自定义模型验证?

本文发布于:2023-11-14 03:56:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586145.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   模型   如何在   NET   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!