How can I make a “RequiredIf” custom valid attribute in vb.net
我正在尝试在vb.net中创建一个customvalidation属性
1 2 3 4 5 6 7 8 9 10 | 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 |
在我的界面上
1 2 3 4 5 6 7 8 9 | Imports System.ComponentModel.DataAnnotations Imports EventRules Namespace Contracts Public Interface IEvent Property EventIsInOneWeek As Boolean <CustomRule()> Property AdditionalProperty |
所以,我得到的错误是eventinoneweek,并说"引用非共享成员需要对象引用"
编辑:正在传递的对象与"eventinoneweek"不同,我只希望在eventinoneweek为true时需要它。
编辑:也更完整地更新了代码
如上所述——我正在寻找的简单解决方案是通过
在我的基本业务逻辑中:
1 2 3 4 5 6 7 8 | 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 |
在我的业务逻辑中,对象本身
1 2 3 4 5 | 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 |
我正在将我的基本逻辑传递到我的业务对象中,它似乎工作得很好,但不幸的是,它不会像
这也允许我验证规则在传递validationcontext时提供一些重用性。