使用 DataAnnotations 验证类
我有一个类,用于在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我过去使用数据注释来获取注释对象上的所有错误的方法(它可以使用一些改进,但这是一个很好的起点:
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:
.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