How to Validate Forms with ASP.NET MVC 2 Data Annotations: Listing 3.

Server-Side Custom Validator for WithinDays()

<DisplayName("Anniversary Date")>
        '<Range(GetType(DateTime), "01/01/2000", "12/31/2010")>
 <WithinDays(PriorDays:=-30, SubsequentDays:=30, ErrorMessage:=
   "Date Must be Within 30 Days")>
        Public Property AnniversaryDate As Object
    End Class
    Public Class WithinDaysAttribute
        Inherits ValidationAttribute

        Public Property PriorDays As Integer
        Public Property SubsequentDays As Integer
        Private ParmDate As DateTime

        Public Overrides Function IsValid(ByVal value As Object) 
          As Boolean
        If IsNothing(value) Then _
        Return False
        If (DateTime.TryParse(value.ToString(), ParmDate) = False) 
        Then Return False

            Dim WithinRange As Boolean =
                (ParmDate >= DateTime.Now.AddDays(PriorDays)) And
                (ParmDate <= DateTime.Now.AddDays(SubsequentDays))

            Return WithinRange
        End Function
    End Class
comments powered by Disqus