Validating Sections of a Page... Again.
The other day I described how to check the values of individual validation controls on a page rather than the entire page. It worked fine, but it meant writing blocks of code that I found kinda klunky (see that post for an example).
Jon Galloway pointed me to an article that Enables/Disables the validation controls on a page which are bound by certain placeholder tags. The disadvantage is having to disable Client-side validation on some browsers. Jon said that it required a different naming convention, but it doesn't.
But, it got me thinking that if a naming convention were required -- say a certain prefix for each section -- then an even simpler solution would be possible. And it doesn't require disabling anything.
Here's how a better solution works:
private Boolean ValidateSection(String prefix) {
foreach (Object v in Page.Validators) {
// Ignore the "System.Web.UI.WebControls." part
String valType = v.GetType().ToString().Remove(0,26);
switch (valType) {
case ("RegularExpressionValidator"):
System.Web.UI.WebControls.RegularExpressionValidator v1 = (System.Web.UI.WebControls.RegularExpressionValidator)v;if ((v1.ID.StartsWith(prefix)) && (!v1.IsValid)) return false; break; <BR> [... other cases left out, get the download below ...] default: <BR> throw new Exception( <BR> "Unknown validator type:",v.GetType().ToString() ); <BR> break; }
} return true; }
The code runs through the Validation controls in a page, which are neatly found in one place: Page.Validators. For each, check the prefix against the one passed in and the validity of the control. One false invalidates the works.
Then instead of calling Page.IsValid or the lengthy block required in my earlier blog, you can use:
if (ValidateSection("Client")) {}
Sure it requires giving validation controls certain prefixes (“Client*” in the above example), but that's something I usually do per section anyway. Simple, eh? Enjoy!