使用属性进行验证
比方说,我有这个简单的类:
public class User
{
[Required(AllowEmptyStrings = false, ErrorMessage="EmailIsRequired"]
public string EmailAddress { get; set; }
}
我知道如何在 System.ComponentModel.DataAnnotations 命名空间中使用 Validator.TryValidateProperty 和 Validator.TryValidateObject。为了使其工作,您需要要验证的对象的实际实例。
但现在,我想在没有 User 类实例的情况下验证某个值,例如:
TryValidateValue(typeof(User), "EmailAddress", "[email protected]");
目标是我想在实际实例化对象本身之前测试一个值(原因是我只允许有效的域实体被创建)。所以实际上我想在类而不是实例上使用验证属性。
有什么想法可以做到吗?
谢谢!
编辑:同时我决定不使用数据注释,而是使用 http://fluidation.codeplex.com 这样验证被移到实体之外。这样,可以从实体以及我的命令处理程序内部触发验证。由于使用了流畅的符号,验证本身看起来也更具可读性。
I have, let's say, this simple class:
public class User
{
[Required(AllowEmptyStrings = false, ErrorMessage="EmailIsRequired"]
public string EmailAddress { get; set; }
}
I know how to use Validator.TryValidateProperty and Validator.TryValidateObject in the System.ComponentModel.DataAnnotations namespace. In order for this to work, you need an actual instance of the object you want to validate.
But now, I want to validate a certain value without an instance of the User class, like:
TryValidateValue(typeof(User), "EmailAddress", "[email protected]");
The goal is that I want to test a value before actually having to instantiate the object itself (the reason is that I only allow valid domain entities to be created). So in fact I want to use validation attributes on classes instead of instances.
Any ideas how that could be done?
Thanks!
EDIT: meanwhile I decided not to use data annotations, but instead use http://fluentvalidation.codeplex.com so that validation is moved outside of the entities. This way validation can be triggered from within the entities as well as my command handlers. The validation itself looks more readable too, thanks to the fluent notation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是如何使用 TryValidateValue< 的示例/a> 方法:
Here's an example of how you could use the TryValidateValue method: