Learning about Validation
In this example, we extend our calculator application to include validation.
As we mentioned earlier, Forms will go through a validation process just before it executes
any Actions, if needed. If the Control that triggers the Action has its
CausesValidation property set to "true", then before executing the Action, the Form will
go through every visible control in the entire Form and call Validate(). Only after ensuring
that every control is valid, will the Form go ahead and execute the assigned Action.
Otherwise, every Control that had its validate() fail will have its ValidationError property
set with the appropriate error message.
What the validation checks for is dependent on the control you are using. In general,
Controls that have their Required property set to "true" will check to ensure that data
was at least entered or selected. Some controls have additional rules. For example, we'll use
IntegerTextBox here to have Forms ensure that the data entered in our two textboxes are
So we will utilize the FormBase's validation in our application by doing the following:
- Set our btnCalculate button's CausesValidation property to true
- Use IntegerTextBox classes
- For those textboxes, we will use renderWithError() instead of render() in the HTML
template code. This is because render() only renders the control, itself, with no
other mark up or placeholders. renderWithError() will be sure to render any error/warning
messages for that control if needed.
- Lastly, we will add our first "business rule": ensure that the user does not divide by 0.
This rule will be implemented as an if statement in the formValidate method.
For more advanced uses, CausesValidation can also be set to ControlBase::CAUSES_VALIDATION_SIBLINGS_AND_CHILDREN
or ControlBase::CAUSES_VALIDATION_SIBLINGS_ONLY. This functionality is geared for developers who are creating more
complex Forms with child controls (either dynamically created, via custom composite controls, custom Panels, etc.),
and allows for more finely-tuned direction as to specify a specific subset of controls that should be validated, instead
of validating against all controls on the form.
SiblingsAndChildren specifically validates all sibling controls and the children of the control that is triggering
the action, while SiblingsOnly specifies to validate the triggering control's siblings, only. One place this is useful for
is in dialogs. Since a dialog is an HTML object that overalys an HTML Form, you only want to validate the controls in the dialog when
its showing, rather than all the controls in the entire form.