如何在 vb.net 中创建 "RequiredIf" 自定义有效属性

How can I make a "RequiredIf" custom valid attribute in vb.net

我正在尝试在 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 并显示 "Reference to a non-shared member requires an object reference"

编辑:传入的对象 属性 不同于 'EventIsInOneWeek',我只希望在 EventIsInOneWeek 为真时才需要它。

编辑:还更完整地更新了代码

如上所述——我一直在寻找的简单解决方案是使用 validationContext 传递整个业务对象。但是,这暴露了我系统中的一些安全漏洞,因此我创建了这个解决方法。

在我的基本业务逻辑中:

Public Overridable Function CheckRules() As Boolean
    Me.Errors = New List(Of ValidationRules)()
    Return Me.Validate(Me.Errors)
End Function
...
Public Overridable Function Validate(validationContext As ValidationContext) As IEnumerable(Of Validation Result) Implements IValidateObject.Validate
     Return Nothing
End Function

并且在我的对象本身的业务逻辑中

Protected Overrides Function Validate(validationContext As ValidationContext) As IEnumerable(Of Validation Result)
    Dim results = New List(Of ValidationResult)()  
    'valiation conditionals here
    Return results
End Function

我正在将我的基本逻辑传递到我的业务对象中,它似乎运行良好,不幸的是它不会像 CustomValidationAttributes 那样自动生成前端验证。

这也让我的 validationRules 有一点可重用性,这是在传入 validationContext 时无法提供的。