使用属性进行验证

发布于 2024-12-12 17:13:11 字数 862 浏览 0 评论 0原文

比方说,我有这个简单的类:

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 技术交流群。

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

发布评论

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

评论(1

却一份温柔 2024-12-19 17:13:11

以下是如何使用 TryValidateValue< 的示例/a> 方法:

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

class Program
{
    static void Main()
    {
        var value = "[email protected]";

        var context = new ValidationContext(value, null, null);        
        var results = new List<ValidationResult>();
        var attributes = typeof(User)
            .GetProperty("EmailAddress")
            .GetCustomAttributes(false)
            .OfType<ValidationAttribute>()
            .ToArray();

        if (!Validator.TryValidateValue(value, context, results, attributes))
        {
            foreach (var result in results)
            {
                Console.WriteLine(result.ErrorMessage);
            }
        }
        else
        {
            Console.WriteLine("{0} is valid", value);
        }
    }
}

Here's an example of how you could use the TryValidateValue method:

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

class Program
{
    static void Main()
    {
        var value = "[email protected]";

        var context = new ValidationContext(value, null, null);        
        var results = new List<ValidationResult>();
        var attributes = typeof(User)
            .GetProperty("EmailAddress")
            .GetCustomAttributes(false)
            .OfType<ValidationAttribute>()
            .ToArray();

        if (!Validator.TryValidateValue(value, context, results, attributes))
        {
            foreach (var result in results)
            {
                Console.WriteLine(result.ErrorMessage);
            }
        }
        else
        {
            Console.WriteLine("{0} is valid", value);
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文