【发布时间】:2015-04-01 19:36:59
【问题描述】:
我正在尝试在 VB.NET 中创建 customValidAttribute
Namespace EventRules
Public Class CustomRuleAttribute
Inherits ValidationAttribute
Protected Overrides Function IsValid(value As Object, validationContext as validationContext) As ValidationResult
If EventIsInOneWeek = True Then
'Property is required
End If
Return New ValidationResult(Me.FormatErrorMessage(validationContext.DisplayName))
End Function
在我的界面中
Imports System.ComponentModel.DataAnnotations
Imports EventRules
Namespace Contracts
Public Interface IEvent
Property EventIsInOneWeek As Boolean
<CustomRule()>
Property AdditionalProperty
所以,我在 EventIsInOneWeek 上遇到的错误是“对非共享成员的引用需要对象引用”
编辑:传入的对象是与“EventIsInOneWeek”不同的属性,我只希望在 EventIsInOneWeek 为真时才需要它。
编辑:还更完整地更新了代码
【问题讨论】:
-
EventIsInOneWeek 在哪里?另一个班级?另一个对象?您必须引用具有 EventIsInOneWeek 属性的对象。
-
EventIsInOneWeek 与我的其他属性在同一个对象中。我可以在这里扩展我的代码,给我一秒钟
-
我对验证属性不太熟悉。但是,我想您必须将
value转换为IEvent并访问此对象的EventIsInOneWeek。 -
@Nico 当我这样做时——我失去了对需要验证的特定对象的引用,而只是在这里传入一个模型。这是因为在 System.ComponentModel.DataAnnotations 中,函数 IsValid 可以用
(object)或(object, validationContext)覆盖,并且对象必须是紧跟<CustomValidationAttribute>之后的行上的特定属性至少我认为这是准确的 -
好的,我明白了。
validationContext的ObjectInstance是否为您提供所需的对象?