Art Of Programming

musings by Dmytrii Nagirniak

WebForms Validate and Validate With Group

.NET 2.0 introduced a new method Validate on the page. It has additional parameter: validation group. As we all know and name suggests it indicates the group the validation should be applied to.
But how do old Validate and new Validate(validationGroup) methods work together?
Here is the flow when the the validation is executed via Validate(validationGroup) (it is the case with controls that have CausesValidation property):
  1. Validate(validationGroup) is executed.
  2. It retrieves all the validators for the given group.

    1. Comparison is case-insensitive.
    2. By default validationGroup is empty string for all validators and the controls that cause the validation.

  3. If the validationGroup is default one (eg: empty string) AND number of validators for the empty group is the same as total number of validators:

    1. YES: Fallback to the .NET 1.1 Validation without validation group.
    2. NO: Execute each validator retrieved in step 2.
The flow if you call validation using the old way: Validate without parameters. It just executes the step 1.1 described above.
So the moral is, if you override the Validate without parameters to perform custom logic it won’t necessarily be called every time. So the moral of the story is:
  1. Use only one validation method. And it must be Validate with validationGroup as it is called automatically by the controls and at the step 3.2 ignores the default (Validate without parameters) method.
  2. Override only one validation method to avoid double validation logic (which should be the same as in point 1).
  3. Make sure you manually call only one validation method. Again according to 1.
So we really should keep this in mind as forgetting to call Validate() instead of Validate(string.Empty) will break the validation, and very likely to be found in production as WebForms testing is painful.
I think this approach is wrong. It’s aim was to maintain backwards compatibility (which works up to some point). But it had one of the following ways:
  1. I would better prefer to have broken interface and removed/obsolete old Validate (without parameter) method.
  2. To avoid breaking functionality the default Validate had to call Validate(string.Empty) and not other way around.
So after migrating to ASP.NET 2.0 still fighting WebForms… and its “compatibility” which “hidden incompatibility”.

Comments