使用属性进行验证 [英] Validation using attributes

查看:91
本文介绍了使用属性进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类,

public class User
{
  [Required(AllowEmptyStrings = false, ErrorMessage="EmailIsRequired"]
  public string EmailAddress { get; set; }
}

我知道如何在System.ComponentModel.DataAnnotations命名空间中使用Validator.TryValidateProperty和Validator.TryValidateObject.为了使它起作用,您需要要验证的对象的实际实例.

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.

但是现在,我想在没有User类实例的情况下验证某个值,例如:

But now, I want to validate a certain value without an instance of the User class, like:

TryValidateValue(typeof(User), "EmailAddress", "test@test.com");

目标是我要在实际实例化对象本身之前测试一个值(原因是我只允许创建有效的域实体).因此,实际上,我想在类而不是实例上使用验证属性.

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?

谢谢!

同时,我决定不使用数据注释,而是使用 http://fluentvalidation.codeplex.com 以便将验证移到实体之外.这样,可以从实体以及我的命令处理程序中触发验证.借助流利的符号,验证本身也看起来更具可读性.

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.

推荐答案

以下是如何使用

这篇关于使用属性进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆