流利的验证和库 [英] Fluent Validation and libraries

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

问题描述

在寻找的东西完全不同的一天,我偶然发现了两个库做流利验证在.NET。 因为到目前为止,我做我的验证,使用常规的条件和分支语句的概念似乎有趣的(如果,否则,箱等)。

While looking for something totally different the other day, I have stumbled upon two libraries for doing Fluent Validation in .NET. The concept seems interesting since so far I am doing my validations using the usual conditional and branching statements (if, else, case, etc).

在具体地,它使比较容易链在某些条件,这可能导致在某些情况下,在较短的code代表复杂的条件下,并以嵌入多个错误消息为在同一个对象的每个违规。

In particularly, it makes relatively easy to chain some conditions which could result in some cases in shorter code for complex conditions, and to embed several error messages for each violations in the same object.

这是说,是不是也做了code看起来比C#更详细的通常,有点像T-SQL有时可能...并没有这导致code到有不一致的外观和感觉?

That said, isn't it also making the code look more verbose than C# usually is, a bit like T-SQL can be at times... and doesn't this cause the code to have an inconsistent look and feel?

总之,你有什么感想流利验证的,如果你喜欢它,它库你有没有发现是最好的呢?到目前为止,我已经看 HTTP://tnvalidate.$c$cplex.com/ HTTP://fluentvalidation.$c$cplex.com/ 这似乎更多或更少相当于在乍一看...

In short, what do you think of Fluent Validation and if you like it, which library have you found to be the best for it? So far, I have looking at http://tnvalidate.codeplex.com/ and http://fluentvalidation.codeplex.com/ which seem more or less equivalent at the first glance...

感谢。

推荐答案

我用,我已经出版了我自己的验证库的这里

I'm using my own validation library that I've published here.

与你建议这两个不同的是,在验证被放入单独的验证类。您可以创建和忘记的验证类,它们会自动通过验证库发现的。

The difference with the two that you suggested is that the validations are put into separate validation classes. You can create and forget the validation classes, they are automatically discovered by the validation library.

public class MyModelValidator : FluentValidator<MyModel>
{
  public MyModelValidator()
  {
    Property("FirstName").Required();
    Property("LastName").Required().Min(15);
  }
}

这也很容易添加使用你自己喜欢的本地化libray本地化支持(如字符串表)

It's also easy to add support for localizations using your very own favorite localization libray (such as a string table)

public class StringTableProvider : ILanguagePrompts
{
    public string this[string modelName, string propertyName]
    {
        get { return Get(modelName, propertyName) ?? "[" + propertyName+ "]"; }
    }

    public string Get(string modelName, string propertyName)
    {
        return Resource1.ResourceManager.GetString(modelName + "_" + propertyName);
    }
}

和配置:

Validator.LanguageHandler = new StringTableProvider();

实际验证是这样做的:

The actual validation is done like this:

User user = new User();
user.FirstName = "Jonas";

var errors = Validator.Validate(user);
if (errors.Count > 0)
{
    // Handle the errors in any way you like.
    // both property names (localized and actual property name) and localized error message is accessible.
}

这篇关于流利的验证和库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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