类级验证
我正在使用 DataAnnotations
< 验证类/a> 实用程序。
我有一个具有 Title
属性和 Item
属性的类。 我想应用 RequiredAttribute
到 Title
属性,但仅当 Item
属性为 null 时才应无效;如果使用对象设置 Item
属性,则不需要 Title
。
简而言之,我想要 RequiredAttribute
仅在满足类中的条件时进行验证。
这怎么办呢。
更新
由于我没有找到其他方法,并且由于我通常不需要经常使用此功能,因此我决定使用类级验证器来实现它的粗略方法。 我的问题是,有没有办法手动更新用户界面,使标题文本框带有红框,即使其无效?
更新2
我希望类级验证器在一个字段上进行总结。 例如,我必须字段 Cost 和 SalesPrice,我想确保 SalesPrice >否则,成本并使 SalesPrice 无效,我不希望在类级别出现全局验证错误。
我更喜欢用 xamly 的方式来做。
I am validating a class with DataAnnotations
utils.
I have a class that has a Title
property and an Item
property.
I want to apply a RequiredAttribute
to the Title
property but it should be invalid only if the Item
property is null; if the Item
property is set with an object, the Title
is not required.
In short words, I want the RequiredAttribute
to validate only if a condition in the class is satisfied.
How can this be done.
Update
As I didn't find other way, and since I usually don't need this functionality so often, I decided to make it the rough way using a class-level validator.
my question is then, is there a way to manually update the UI to make that Title TextBox with a red frame, i.e. to invalidate it?
Update 2
I want the class-level validator to summarize on a field.
For example, I have to fields Cost and SalesPrice, I wanna make sure that SalesPrice > Cost and invalidate the SalesPrice otherwise, I don't want a global validation error on the class level.
I prefer to do it the xamly way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过为类创建自定义验证属性来完成此操作。不幸的是,据我所知,分配给属性的 DataAnnotation 属性无法访问父类的其他属性,因此需要创建一个类验证器。
使用 System.ComponentModel.DataAnnotations 命名空间,您将需要创建继承自 ValidationAttribute 的自定义属性类并覆盖 IsValid 方法(我没有测试下面的代码,但它应该可以帮助您继续):
进一步挖掘,似乎虽然交叉现场验证不可能开箱即用,可以通过扩展框架来支持它来实现。请参阅本文有关详细信息,希望这会添加到 MVC 的未来版本中。
You may be able to do this by creating a custom validation attribute for the class. Unfortunately DataAnnotation attributes assigned to properties cannot access other properties of the parent class as far as I am aware hence the need to create a class validator.
Using the System.ComponentModel.DataAnnotations namespace you will need to create you custom attribute class inheriting from ValidationAttribute and override the IsValid method (I have not tested the code below but it should get you going):
Digging a little further it appears that whilst cross field validation it not possible out of the box it can be achieved by extending the framework to support it. See this article for details, hopefully this will be added to future versions of MVC.
好吧,在 MVC 中很难实现属性级别的条件验证。但你可以扩展框架或者你可以使用其他一些库来实现目标。我在我的项目中成功地使用了 nick 的万无一失的验证来进行条件验证。你可以在这里看看
well, on property level contingent validations are hard to achieve in MVC. but u can extend the framework or u can use some other library to achieve the goal. i m using foolproof validation by nick successfully for contingent validations in my project. u can take a look at it here