Custom Validator Example

[csharp]
using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace SocialAnimal.Web.UserControls
{
/// <summary>
/// If ControlToValidate has a value then DependantControl
/// must also have a value
/// </summary>
public class DependantFieldValidator : CustomValidator
{
private string _dependantControl = null;
private bool _showAlertBox = false;

[Description(@”If true, will show an alert box if the control validates false, otherwise will display an inline message”),
Category(“Behavior”)]
public bool ShowAlertBox
{
get { return _showAlertBox; }
set { _showAlertBox = value; }
}

[Description(@”The name of the dependant control which must have
a value if ControlToValidate has a value”),
Category(“Behavior”)]
public string DependantControl
{
get { return _dependantControl; }
set { _dependantControl = value; }
}

/// <summary>
/// Generate the client side code to validate the Controls
/// </summary>
/// <param name=”e”></param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string controlToValidateId = Page.FindControl(ControlToValidate).ID;
string dependantControlId = Page.FindControl(_dependantControl).ID;

StringBuilder js = new StringBuilder();

//Generate the Validation Event to Validate control
js.Append(@”<script language=””JavaScript””>”);
js.Append(@”function DependantFieldValidateControl(val, args) {var msg=”;args.IsValid = true;”);

js.Append(@”if (document.all[‘” + controlToValidateId + “‘].value != ”){“);
js.Append(@” if (document.all[‘” + dependantControlId + “‘].value == ”){“);

// If AlertType is set to Alert else build the error message string to be displayed
js.Append(@” msg=msg+'” + ErrorMessage + “‘;}if(msg!=”){“);

if (ShowAlertBox)
{
js.Append(@”alert(msg);”);
}
else
{
js.Append(@”args.IsValid = false;”);
}

js.Append(@”}}}</script>”);

Page.RegisterClientScriptBlock(“funcValidate”, js.ToString());
}

protected override void OnInit(EventArgs e)
{
base.OnInit(e);

this.ClientValidationFunction = “DependantFieldValidateControl”;
}

protected override bool EvaluateIsValid()
{
bool retVal = true;

// Get the control value; return true if it is not found.
string controlValue = GetControlValidationValue(ControlToValidate);
if (controlValue != string.Empty)
{
string dependantValue = GetControlValidationValue(DependantControl);
if (dependantValue == string.Empty)
{
retVal = false;
Control c = Page.FindControl(DependantControl);
if (c != null)
{
if (c is TextBox)
{
TextBox tb = (TextBox)c;
tb.Enabled = true;
}
}
}
}

return retVal;
}
}
}
[/csharp]

Advertisements

2 thoughts on “Custom Validator Example

  1. Mike says:

    Al:

    This may be a stupid question, but, using your code in this post, in the OnPreRender sub, how would you go about getting the id of a control in an EditItemTemplate of a gridview. I keep getting “Object reference not set to an instance of an object.”, I’m assuming b/c the OnPreRender is firing before the page has a chance to render the gridview, or any of it’s child controls. I tried the following:

    Dim grid As New GridView()
    grid = CType(Page.FindControl(“GridView1”), GridView)

    Dim _controlToValidate As New Control()
    _controlToValidate = CType(grid.TemplateControl.FindControl(“TextBox1”), Control)

    Thanks.

  2. alpriest says:

    Mike,

    I’ve just tried my code in a GridView. There’s a slight bug in it – on lines 42, 43, if you change the Page.FindControl to just FindControl it finds the controls by the ID correctly.

    Note that the CustomValidator base class requires that you specify the ID (e.g. TextBox1), rather than the ClientID of $gridview1$ctl0$textbox or similar. Therefore just using the ID should work fine.

    If you need the ClientID of the control in the EditItemTemplate, then you can see it in the GridView PreRender method. See example below:

            protected void GridView1_PreRender(object sender, EventArgs e)
            {
                // hook up the textbox to the requiredfieldvalidator
                GridView gv = sender as GridView;
                if (gv != null)
                {
                    if (gv.EditIndex > -1)
                    {
                        TextBox tb1 = gv.Rows[gv.EditIndex].Controls[0].FindControl("TextBox1") as TextBox;
                        string clientId = tb1.ClientID;
                    }
                }
            }
    

    Hope this helps!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s