C#•Validate With Expression

Listing 3. This class validates a column based on an aggregate expression. It can set the error for a single row or for all rows that match the filter criteria. This class can support more complex business rules for client-side validation.

[Serializable ()]
public class ComputeValidator : Validator
{
   private string _formula; // The formula
   private object _result; // What to expect
   // which column to use for the filter
   private string _filterColumn;
   // Mark all rows matching the filter?
   private bool _markAllRows; 

   public ComputeValidator (string t, 
      string c, string m,
      string formula,
      string filterColumnName,
      object result,
      bool markAll) :
      base (t, c, m)
   {
      _formula = formula;
      _filterColumn = filterColumnName;
      _result = result;
      _markAllRows = markAll;
   }

   public override void Validate
      (DataSet ds, DataRow r, 
      DataColumn c, object newVal)
   {
      StringBuilder filter= new 
         StringBuilder(_filterColumn);
      if (_filterColumn.Length > 0)
      {
         filter.Append ("='");
         filter.Append 
            (r[_filterColumn].ToString 
            ());
         filter.Append ("'");
      }
      object result = r.Table.Compute 
         (_formula, filter.ToString ());
         
      if (_markAllRows)
      {
         DataView v = new DataView 
            (r.Table);
         v.RowFilter = 
            filter.ToString ();

         if (_result.Equals (result))
         {
            foreach (DataRowView row 
               in v)
            {
               row.Row.
                  SetColumnError 
                  (c, "");
               row.Row.
                  RowError = "";
            }
         } 
         else         
         {
            foreach (DataRowView row 
               in v)
            {
               row.Row.
                  SetColumnError 
                  (c, 
                  _errMessage);
               row.Row.RowError = 
                  _errMessage;
            }
         }
      } 
      else
      {
         if (_result.Equals (result))
         {
            r.SetColumnError (c, "");
            r.RowError = "";
         } 
         else         
         {
            r.SetColumnError (c, 
               _errMessage);
            r.RowError = _errMessage;
         }
      }
   }
}