A time saving class that writes them all for you
I don't know about you, but I seem to write RequiredFieldValidators (referred to as RFVs from here on out) on pretty much every project I work on. You just can't count on the user to fill stuff out unless you make them do it. On a recent project, I was going to have to write a TON of RFVs, and to top if off, this form was likely going to change a lot, so I didn't want to have to re-write them later over-and-over again. So I figured out a way for .Net to do the work for me... isn't that the point of programming? As long as you follow good naming conventions, all you need to do is call the function and blam, you have RFVs.
Generally, I just use RFVs for DropDownLists and TextBoxes (DDLs and TBs from here on out), so I came up with a class that finds DDLs and TBs and makes RFVs for them. BUT, I soon realized that I don't want to have everything be required, so I made the class look for only those with '_req' (required) on the end of their ID property. So, a TB with ID="txtFirst_Name" will not get a validator, but one with ID="txtFirst_Name_req" will.
With that out of the way, I wanted it to give you somewhat readable and clear error messages, so the validators will be very descriptive and readable if you use good naming conventions. For example, the DDL with ID="ddlCity_and_State_req" or ID="City_and_State_req" will both have a validator with the message "Must select a City and State". As you can see, the prefixes, if present, are trimmed (which you can specify if you want, the defaults are 'txt' and 'ddl') and underscores (_) are replaced by spaces ( ).
The function takes in:
- Panel pnl - Required - The Panel you want this to run on
- string[] trimFromFront - optional - An array of prefixes you wanted trimmed off for the ErrorMessages; default is 'ddl' and 'txt'
- string defaultDropDownValue - optional - a string that is considered 'empty' in a DDL; default is '-'
- string validationGroup - optional - the ValidationGroup that you want these controls to validate to; default is null
Examples of how to call the code (remember to pass null if you are not specifying an optional value):
// all defaults, but you DO have to include the HtmlForm of your page
validators.setupValidators(pnl, null, null, null);
// defaults, but sets the ValidationGroup
validators.setupValidators(pnl, null, null, "valGroup1");
// sets the DropDown 'empty' state to 'select'
validators.setupValidators(pnl, null, "select", null);
// trims off prefixes 'TextBox', and 'DropDown' in the ErrorMessage
validators.setupValidators(pnl, new string[] {"TextBox","DropDown"}, null, null);
*IMPORTANT this does require a ValidationSummary control on your page, otherwise you will not see the errors, though they will be working. This was the only way to keep the output clean as teh RFVs are added to the bottom of the page. Also, I recommend calling this in your OnInit event.
Here is the code if anyone wants to check it out: Show/Hide
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
/// <summary>
/// Automatically populates required field validators for all DropDownLists and TextBoxes that have IDs that end in '_req'.
/// ** Each field that you want to be required MUST have an ID ending in '_req', that is how the program decides you want a requiredFieldValidator
/// ** You need to have a ValidationSummary to see the errors
/// trimFromFront, defaultDropDownValue and validationGroup can be null
///
/// This class will automatically format your error message to an understandable error message *if you use proper naming conventions:
/// -A TextBox 'txtFirst_Name_req' will give the error message 'First Name is required'
/// -A DropDownList 'ddlCity_and_State_req' will give an error message 'Must select a City and State'
/// *note that the prefixes 'ddl' and 'txt' are trimmed by default (you can change this) and all '_' characters are replaced by spaces
/// </summary>
public class validators
{
public static void setupValidators(HtmlForm form, string[] trimFromFront, string defaultDropDownValue, string validationGroup)
{
// PREFIXES_TO_TRIM is the stuff you want to cut off for formatting of your validators (i.e., cut the 'ddl' of ddlStates, or the 'txt' off of txtLastName)
string[] PREFIXES_TO_TRIM = trimFromFront==null ? new string[] { "ddl", "txt" } : trimFromFront;
// EMPTY_DROP_DOWN is the value you want to be considered 'empty' in your DropDownLists
string EMPTY_DROP_DOWN = defaultDropDownValue == null ? "-" : defaultDropDownValue;
IEnumerable<Control> cc = form.Controls.Cast<Control>(); // collects all controls in your HtmlForm
List<Control> validators = new List<Control>(); // collection of the validators you make
foreach (Control c in cc)
{
if ((c.ID != null && c.ID.ToString().Contains("_req")) && ((c.GetType().ToString().Equals("System.Web.UI.WebControls.DropDownList")) || c.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")))
{ // only cares about the controls you specify by a trailing '_req' in the ID AND this will only make validators for DropDownLists and TextBoxes, all others are ignored;
string controlName = c.ID;
foreach (string s in PREFIXES_TO_TRIM) // cuts off any prefixes you have for neatness
controlName = (controlName.Substring(0, s.Length).Equals(s)) ? controlName.Substring(s.Length, (controlName.Length - s.Length)) : controlName;
controlName = controlName.Substring(0, controlName.Length - 4); // cuts off the '_req' for formatting
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.Display = ValidatorDisplay.None; //none because you are using a summary - only way to do it neatly
rfv.ID = "rfv" + controlName; // nicely formats ID (no real function I know :P)
rfv.ControlToValidate = c.ID;
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.DropDownList")) rfv.InitialValue = EMPTY_DROP_DOWN;
if (validationGroup != null) rfv.ValidationGroup = validationGroup; // if you specify a validationGroup
rfv.EnableClientScript = true; // just in case
// next line replaces all '_' characters in your ID with spaces for nice forrmatting of error messages
rfv.ErrorMessage = c.GetType().ToString().Equals("System.Web.UI.WebControls.DropDownList") ? "Must select a " + controlName.Replace('_', ' ') : controlName.Replace('_', ' ') + " is required";
validators.Add(rfv);
}
}
foreach (Control c in validators) // add them to your program
{
try { form.Controls.Add(c); }
catch (Exception ex)
{ form.Controls.Add(new LiteralControl("<div style=\"padding:10px;background:#FFE5E5;\">Error" + ex.Message + "</div>")); }
}
}
}
Download just the class here:
Full working example (see it in action):