PrimalForms 2011: Validating the Form – Part 1

A good user interface will validate user input to ensure it is in the correct format. This may come in the form of simply checking if there is an entry for a field, such as a name or a more complex task such as validating an email address. Thankfully WinForms has built in mechanisms to help facilitate data validation.

Each control has the following events and properties that are used to validate a form:

Validation Events:


This event occurs when the control is validating. Validation on a control is triggered when the control loses focus.

Use this event to provide custom validation for any input control, such as a TextBox. The Validating event passes a [System.ComponentModel.CancelEventArgs] object as a parameter to the event block, which you can access this by using the $_ variable.

#Event Argument: $_ = [System.ComponentModel.CancelEventArgs]
    #If Validation fails tell the event to stop
    $_.Cancel = $true

Set $_.Cancel to $true when the validation is successful and you wish to continue.

Set $_.Cancel to $false if you wish to cancel the action because of a validation failure.

If the Cancel property is set to True in the Validating event, all events that would usually occur after the Validating event are suppressed. In other words, the validating control will retain the focus until the user provides the correct format, even if the user clicks another control such as a button or textbox. I.e., the caret will remain in the textbox until the user enters the correct format.

Important: Never attempt to set the Focus of a control in this event because it can cause the script to hang.


This event occurs when the control is finished validating. Use this event to handle any needed upkeep after successfully validating the control.

Note: If the Validation was canceled in the Validating Event, then this event will not be called.


Validation Properties:


This property indicates whether the control causes validation to be performed on any controls that require validation when it receives focus. A typical case where CausesValidation property is set to False is when there is a cancel button. There is no need to validate a control that loses focus when the user wishes to cancel out of the form; therefore, the button’s CausesValidation property can be set to false.


Next: Part 2 – How to validate a control