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