Below is the C# code for an ASP.NET required validator web control that requires a specified set of controls to be all populated, or all empty. It inherits from the RequiredFieldValidator ASP.NET class, so it essentially works the same way, it just treats the set of controls you specify as if they were one control (in the sense of requirement).
To use this code, I'd recommend placing it into your own library (because you'll create your own to add to this one -- it's easy!) of custom web controls (in VS.NET, a Class Library), and then add your library as a reference in your web project(s). In your web project, to specify the controls that are part of the set, add their names to the ControlNames collection:
anrvOptionalContact.ControlNames.Add("txtOptionalContact")anrvOptionalContact.ControlNames.Add("ddlOptionalContactType")
Notes:
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections.Specialized; using System.ComponentModel; namespace Custom { /// /// Required validator that validates a set of controls requiring that they are /// all populated or all empty /// public class AllOrNothingRequiredValidator : RequiredFieldValidator { private StringCollection _scControlNames; public AllOrNothingRequiredValidator() : base() { _scControlNames = new StringCollection(); EnableClientScript = false; } [ Category("Behavior"), Description("The controls to validate."), TypeConverter(typeof(CollectionConverter)) ] public StringCollection ControlNames { get { return _scControlNames; } set { _scControlNames = value; } } protected override bool ControlPropertiesValid() { return true; } protected override bool EvaluateIsValid() { Control control; int iCounter = 0; string[] aryValues = new string[_scControlNames.Count]; foreach (string sControlName in _scControlNames) { control = Page.FindControl(sControlName); //make sure control exists & is validatable CheckControlValidationProperty(sControlName, "ControlNames"); //add value to array to eval later aryValues[iCounter] = GetValidationProperty(control).GetValue(control).ToString(); iCounter++; } //eval if all are empty or populated bool bAllEmpty = true; bool bAllPopulated = true; foreach (string sValue in aryValues) { if (sValue.Trim().Length == 0) { bAllPopulated = false; } else { bAllEmpty = false; } } return bAllEmpty || bAllPopulated; } } }
Remember Me
Powered by: newtelligence dasBlog 1.8.5223.2
© Copyright 2008, Troy DeMonbreun
E-mail