使用 DataAnnotations 验证类

发布于 2024-08-13 07:01:22 字数 175 浏览 7 评论 0原文

我有一个类,用于在 MVC 中对数据进行建模。我添加了一些 DataAnotations 来标记必填字段,并且使用正则表达式来检查有效的电子邮件地址。如果对象被发回 MVC,并且我有 ModelState 属性,我可以检查该属性以确认该类是否有效,那么一切正常,但如何使用相同的类和数据注释检查该类在 MVC 之外是否有效我已经设置了?

I have a class that I am using to model my data in MVC. I have added some DataAnotations to mark fields that are required and I am using regular expressions to check valid Email Addresses. Everything works fine if the object is posted back to MVC and I have the ModelState property that I can check to confirm that the class is valid but how do I check to see if the class is valid outside of MVC using the same class and Data Anotations that I have already set up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泡沫很甜 2024-08-20 07:01:22

这是我过去使用数据注释来获取注释对象上的所有错误的方法(它可以使用一些改进,但这是一个很好的起点:

public static IEnumerable<ErrorInfo> GetErrors(object instance)    
{
   return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>() 
      from attribute in prop.Attributes.OfType<ValidationAttribute>()
      where !attribute.IsValid(prop.GetValue(instance))
      select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);    
}

Here's a method that I've used in the past with Data Annotations to get all of the errors on an annotated object (it could use some improvements, but it's a good starting point:

public static IEnumerable<ErrorInfo> GetErrors(object instance)    
{
   return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>() 
      from attribute in prop.Attributes.OfType<ValidationAttribute>()
      where !attribute.IsValid(prop.GetValue(instance))
      select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);    
}
无边思念无边月 2024-08-20 07:01:22

.NET 3.5 中似乎没有内置任何内容。不过,如果您可以针对 .NET 4 进行开发,则有一个 Validator 类可以提供您所需的内容:

MSDN 上的验证器类

There doesn't appear to be anything built into .NET 3.5. If you can develop against .NET 4, though, there is a Validator class that provides what you need:

Validator class on MSDN

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文