I would like to know what is the easiest way to have a \"Greater Than\" & \"Lower Than\" validation on a ASP.NET MVC 3 form?
I use unobtrusive JavaScript for client
I don't know if writing your own validator class is the "easiest" way, but that's what I did.
Usage:
Public Property StartDate() As DateTime
Public Property EndDate() As DateTime
Class:
Public Class DateGreaterThanEqualAttribute
Inherits ValidationAttribute
Public Sub New(ByVal compareDate As String, ByVal errorMessage As String)
MyBase.New(errorMessage)
_compareDate = compareDate
End Sub
Public ReadOnly Property CompareDate() As String
Get
Return _compareDate
End Get
End Property
Private ReadOnly _compareDate As String
Protected Overrides Function IsValid(ByVal value As Object, ByVal context As ValidationContext) As ValidationResult
If value Is Nothing Then
' no need to do or check anything
Return Nothing
End If
' find the other property we need to compare with using reflection
Dim compareToValue = Nothing
Dim propAsDate As Date
Try
compareToValue = context.ObjectType.GetProperty(CompareDate).GetValue(context.ObjectInstance, Nothing).ToString
propAsDate = CDate(compareToValue)
Catch
Try
Dim dp As String = CompareDate.Substring(CompareDate.LastIndexOf(".") + 1)
compareToValue = context.ObjectType.GetProperty(dp).GetValue(context.ObjectInstance, Nothing).ToString
propAsDate = CDate(compareToValue)
Catch
compareToValue = Nothing
End Try
End Try
If compareToValue Is Nothing Then
'date is not supplied or not valid
Return Nothing
End If
If value < compareToValue Then
Return New ValidationResult(FormatErrorMessage(context.DisplayName))
End If
Return Nothing
End Function
End Class