Search code examples
vb.netcustomvalidator

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


I am trying to create a customValidAttribute in VB.NET

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

And in my Interface

Imports System.ComponentModel.DataAnnotations
Imports EventRules

Namespace Contracts
Public Interface IEvent

Property EventIsInOneWeek As Boolean
<CustomRule()>
Property AdditionalProperty

So, the error I am getting is on EventIsInOneWeek and says "Reference to a non-shared member requires an object reference"

Edit: The object being passed in is a different property than 'EventIsInOneWeek', and I only want it to be required if EventIsInOneWeek is true.

Edit: Also updated the code more completely


Solution

  • As mentioned above -- the simple solution I was looking for was passing the entire business object in with validationContext. However, this exposes some security flaws in my system, so I created this work-around.

    In my base business logic:

    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
    

    And In my Business logic for the object itself

    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
    

    I am passing my base logic into my Business Object, and it seems to be working well, unfortunately it does not auto generate front-end validation the way CustomValidationAttributes do.

    This also allows me validationRules a little bit of re-usability that would not be afforded when passing a validationContext in.