forX forX - 1 month ago 7
Vb.net Question

custom control validator with same modification

I did the same modification on 3 kind of BaseValidator. I search a way to remove the duplicate code.

I did the same code for RequiredFieldValidator , RegularExpressionValidator and CustomValidator

Public Class CustomValidator
Inherits System.Web.UI.WebControls.CustomValidator

Protected Overrides Sub Render(writer As HtmlTextWriter)

Try
If Not String.IsNullOrWhiteSpace(ControlToValidate) Then
Dim ctv As Control = Me.FindControl(ControlToValidate)
writer.AddAttribute("for", ctv.ClientID)
End If
Catch
End Try

MyBase.Render(writer)

End Sub

Protected Overrides ReadOnly Property TagKey() As System.Web.UI.HtmlTextWriterTag
Get
Return HtmlTextWriterTag.Label
End Get
End Property
End Class

Answer

I ran into the same issue you have with these exact classes; I wanted to add some additional features to the validation controls. The way I ended up sharing some common code was implementing my own classes that inherited from the validator classes and then implementing the shared logic in a utility class. I'm not familiar with VB, so please bear with the C# example.

public static class ValidationUtilities
{
    public static void AddFor(Control validationControl, string controlToValidate, HtmlTextWriter writer)
    {
        if (!string.IsNullOrWhiteSpace(controlToValidate))
        {
            var ctv = validationControl.FindControl(controlToValidate);
            writer.AddAddtribute("for", ctv.ClientID);
        }
    } 
}

class MyRegularExpressionValidator : RegularExpressionValidator
{
    protected override void Render(HtmlTextWriter writer)
    {
        ValidationUtilities.AddFor(this, ControlToValidate, writer);
    }
}

class MyRequiredFieldValidator : RequiredFieldValidator 
{
    protected override void Render(HtmlTextWriter writer)
    {
        ValidationUtilities.AddFor(this, ControlToValidate, writer);
    }
}

You could make the argument that's more work than it's worth for not duplicating a small amount of code, but if you have a lot more, or your duplicated code is complex in some way, this is a way you can share it. Also, I made my utility class static, but there's no reason it couldn't be otherwise.