'
' This is exactly like RequiredFieldValidator
' Except that it only fires if another control is set
'
Public Class RequiredDependentFieldValidator
    Inherits BaseValidator

#Region "Properties"

    Property DependencyControl As String

    Property WhenValue As String

#End Region

    Protected Overrides Sub AddAttributesToRender(writer As HtmlTextWriter)
        MyBase.AddAttributesToRender(writer)

        writer.AddAttribute("evaluationfunction", "RequiredDependentFieldValidatorEvaluateIsValid")
        writer.AddAttribute("data-val-evaluationfunction", "RequiredDependentFieldValidatorEvaluateIsValid")

        writer.AddAttribute("dependency-control", GetControlRenderID(DependencyControl))
        writer.AddAttribute("when-value", WhenValue)

    End Sub

    Protected Overrides Function ControlPropertiesValid() As Boolean
        MyBase.ControlPropertiesValid()
        If DependencyControl = "" Then
            Throw New HttpException("Dependency Control cannot be blank.")
        End If
        If WhenValue Is Nothing Then
            Throw New HttpException("WhenValue must be set.")
        End If
        Return True
    End Function

    Protected Overrides Function EvaluateIsValid() As Boolean
        Dim dependencyValue = GetControlValidationValue(DependencyControl)
        If dependencyValue.ToLower() = WhenValue.ToLower() Then
            Dim value = GetControlValidationValue(ControlToValidate)
            If String.IsNullOrEmpty(value) Then
                Return False
            End If
        End If
        Return True
    End Function

End Class
