Validating Sections of a Page

I built a DataGrid with an EditTemplate to edit records and a FooterTemplate to Add records. I made the footer invisible and put a ButtonLink just below the grid to expand the footer. Then I made an if (IsValid) {}
section around my code to Update a record, and another around my code to Add a record.

The IsValid around the Update code didn't work. The IsValid around the Add code worked fine. This was because the Edit section simply didn't exist while Adding. However, though the Add section was invisible during an Edit, it still existed, and its controls were validated along with the Edit controls during an Update event.

The solution was to use control-level rather than page-level validation. IsValid by itself is equivalent to Page.IsValid. You can also do a FindControl and get the IsValid results of an individual validation control. This is the sort of C# code I used (if you get a crazy gap below, try widening your browser, worked for me):

public void dgCustomer_ItemCommand(Object sender,  System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  switch (e.CommandName)
  {
    case "cmdAddNewCustomer" :
      RequiredFieldValidator valNewFirstNm = ((RequiredFieldValidator)e.Item.FindControl("valNewFirstNm"));

      RequiredFieldValidator valNewLastNm = ((RequiredFieldValidator)e.Item.FindControl("valNewLastNm"));

      RegularExpressionValidator valNewDoB = ((RegularExpressionValidator)e.Item.FindControl("valNewDoB")); 

      if (valNewFirstNm.IsValid && valNewLastNm.IsValid && valNewDoB.IsValid )
      {
        /* Code to add a new Customer */
      }
      break;
    default:
      break;
   }
}

I applied similar code to both the Add and Edit sections even though it was only the Edit that caused trouble. That way if I add another form to the page (perhaps another editable grid), its validation controls won't interfere with these, provided I apply control-by-control validation to it as well.

If this becomes a frequent exercise, it would make sense to build a method that could parse through the children of a given control (like the Footer section or an embedded Panel), look for Validator controls and return their IsValid results ORed together. If anyone out there builds it first, send me a copy!

No Comments