I have a field that may or may not be require based on user preferences which are stored in the database. To handle this I have created a custom validation attribute but I'm not sure how to check to see if the field is actually required based on the user preferences.
I tried setting an "IsRequired" property on my view model via the controller & checking that value in the custom attribute however the property is always false since the validation is firing before the property can be set.
Using data annotations how can I get the "IsRequired" property set before/when the validation kicks off? Should I be checking to see if the field is required once it is already passed to the controller instead of using data annotations?
ViewModel:
Public Class MyViewModel
<MyCustomValidationAttribute("IsMyFieldRequired")>
Public Property MyFieldThatMayOrMayNotBeRequired As String
Public Property IsMyFieldRequired As Boolean
Public Sub New(objectUsedToSetIsMyFieldRequired As UserPreferences)
'Set IsMyFieldRequired based on passed in user preferences
End Sub
End Class
Custom Validation Attribute:
Public Class MyCustomValidationAttribute
Inherits ValidationAttribute
Private _otherPropertyName As String
Public Sub New(otherPropertyName As String)
Me._otherPropertyName = otherPropertyName
End Sub
Protected Overrides Function IsValid(value As Object, validationContext As System.ComponentModel.DataAnnotations.ValidationContext) As System.ComponentModel.DataAnnotations.ValidationResult
Dim basePropertyInfo As System.Reflection.PropertyInfo = validationContext.ObjectType.GetProperty(_otherPropertyName)
Dim isRequired As Boolean = Not CBool(basePropertyInfo.GetValue(validationContext.ObjectInstance, Nothing))
'
If isRequired AndAlso value Is Nothing Then Return New ValidationResult(Me.ErrorMessage)
'
Return Nothing
End Function
End Class