.net Fluent 验证与数据注释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6807472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fluent Validation vs. Data Annotations
提问by SiberianGuy
What are the operative differences between these two validation packages when used for ASP.NET MVC validatation? They seem to have similar objects, all the way to their object names. Is one related to another? What are their differences? In what way do these differences denote different use cases?
当用于 ASP.NET MVC 验证时,这两个验证包之间的操作差异是什么?他们似乎有相似的对象,一直到它们的对象名称。一个与另一个相关吗?它们的区别是什么?这些差异以何种方式表示不同的用例?
- Fluent Validation(3rd party solution)
- Data annotations(Microsoft "baked-in")
采纳答案by Darin Dimitrov
I prefer Fluent Validation:
我更喜欢Fluent 验证:
- It gives me far better control of my validation rules
- Doing conditional validation on different properties is so much easier compared to Data Annotations
- It separates the validation from my view models
- Unit testingis far easier compared to Data Annotations
- It has excellent client side validation support for most standard validation rules
- 它让我更好地控制我的验证规则
- 与数据注释相比,对不同属性进行条件验证要容易得多
- 它将验证与我的视图模型分开
- 与数据注释相比,单元测试要容易得多
- 它对大多数标准验证规则具有出色的客户端验证支持
回答by Marius Schulz
I clearly prefer Data Annotationsbecause ...
我显然更喜欢数据注释,因为......
- all validation rules can be configured in one place in code(within the model metadata class) and don't need to be repeated anywhere else.
- there is excellent support for client side validation(again – without repetition of validation rules!) when using Data Annotationattributes.
- Data Annotationattributes can be testedto ensure they're there.
- there are nice additional validation attributescreated by the community (e.g. Data Annotations Extensions).
- 所有验证规则都可以在代码中的一个地方(在模型元数据类中)配置,不需要在其他任何地方重复。
- 使用数据注释属性时,对客户端验证有很好的支持(再次 - 无需重复验证规则!)。
- 可以测试数据注释属性以确保它们存在。
- 社区创建了一些很好的附加验证属性(例如Data Annotations Extensions)。

