ASP.NET MVC 2 中的验证
我在 ASP.NET MVC 2 中使用数据注释进行验证时遇到一些问题。例如,我有 Address 类:
public class Address
{
public long Id { get; set; }
[Required]
public string City { get; set; }
[Required]
public string PostalCode { get; set; }
[Required]
public string Street { get; set; }
}
和 Order 类:
public class Order
{
public long Id { get; set; }
public Address FirstAddress { get; set; }
public Address SecondAddress { get; set; }
public bool RequireSecondAddress { get; set; }
}
我想始终验证 Order.FirstAddress,但仅当 Order.SecondAddress 时才应验证 Order.SecondAddress。 RequireSecondAddress 设置为 true。
有什么想法吗? :)
克里斯
I have some problems with validation using Data Annotations in ASP.NET MVC 2. For example, I have Address class:
public class Address
{
public long Id { get; set; }
[Required]
public string City { get; set; }
[Required]
public string PostalCode { get; set; }
[Required]
public string Street { get; set; }
}
And Order class:
public class Order
{
public long Id { get; set; }
public Address FirstAddress { get; set; }
public Address SecondAddress { get; set; }
public bool RequireSecondAddress { get; set; }
}
I want to validate Order.FirstAddress all the time, but Order.SecondAddress should be validated only if Order.RequireSecondAddress is set to true.
Any ideas? :)
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用数据注释几乎是不可能的,否则需要编写依赖反射的丑陋代码等......(我想你明白了)。
我建议您查看 FluentValidation。它与集成良好ASP.NET MVC。您的验证逻辑可能如下所示:
您还将受益于拥有一个单独的验证层,该层也可以是 以非常优雅的方式进行单元测试。
That's close to impossible using data annotations or it will require writing ugly code that relies on reflection, etc... (I think you get the point).
I would recommend you looking at the FluentValidation. It has a good integration with ASP.NET MVC. Here's how your validation logic might look like:
You will also benefit from having a separate validation layer which also could be unit tested in a very elegant way.
以下条件验证文章可能会有所帮助:
Following conditional validation articles might help: