Validator.TryValidateObject 可以强制 [CustomValidation] 特性来验证属性吗?
我用 CustomValidationAttribute 装饰了一个类的属性,以验证是否设置了 GUID 值,但是当我尝试使用辅助方法 Validator.TryValidateObject() 强制执行它时,似乎它不调用我的验证逻辑。
当装饰属性的值发生更改时,将触发验证逻辑,但我需要处理用户单击保存按钮而不填写必填字段的情况,因此需要在调用 < 之前强制验证属性运行调用strong>DomainContext.SubmitChanges()。
有趣的是,即使是从 ValidationAtrribute 继承的类也不会由 Validator.TryValidateObject() 运行。
强制执行验证属性的正确方法是什么?
I have decorated a property of a class with a CustomValidationAttribute to validate if a GUID value was set but when I try to force it to be executed by using the helper method Validator.TryValidateObject() it seems that it doesn't invoke my validation logic.
The validation logic is being triggered when the value of the decorated property has changed, but I need to handle the scenario wherein the user clicks the save button without filling up required fields, hence the need to force validation attributes to run before a call to DomainContext.SubmitChanges() is called.
Interestingly, even classes that inherit from ValidationAtrribute isn't being run by Validator.TryValidateObject().
What is the correct way to force validation attributes to be executed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在属性级别应用的自定义验证器必须使用 TryValidateProperty 单独进行验证。
例如
Custom validators applied at the property level will have to be validated separately by using TryValidateProperty.
e.g.
更简单的方法是将 TryValidateObject() 上的最后一个参数 (validateAllProperties) 设置为 true。有关详细信息,请参阅 msdn 文章 。
A more simplistic way of doing this is to set the last parameter (validateAllProperties) on TryValidateObject() to true. See the msdn article for more information.