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

WithinDaysValidator Class to Define the Custom Client Validation Rule

Public Class WithinDaysValidator
    Inherits DataAnnotationsModelValidator(Of WithinDaysAttribute)
    Private _priorDays As Integer
    Private _subsequentDays As Integer
    Private _message As String

    Public Sub New(ByVal metadata As ModelMetadata,
                   ByVal context As ControllerContext,
                   ByVal attribute As WithinDaysAttribute)

        MyBase.New(metadata, context, attribute)

        _message = attribute.ErrorMessage
        _priorDays = attribute.PriorDays
        _subsequentDays = attribute.SubsequentDays
    End Sub

    Public Overrides Function GetClientValidationRules() _
      As IEnumerable(Of System.Web.Mvc.ModelClientValidationRule)

        Dim Rule As New ModelClientValidationRule _
        With {.ErrorMessage = _message, .ValidationType = 
          "withindays"}

        Rule.ValidationParameters.Add("prior", _priorDays)
        Rule.ValidationParameters.Add("subsequent", _subsequentDays)

        Dim ModelClientValidationRule() = {Rule}
        Return ModelClientValidationRule
    End Function
End Class
comments powered by Disqus

Featured

Subscribe on YouTube