PrimalForms 2011: Validating the Form – Part 4

September 23rd, 2011 by David Corrales
Last updated on September 23rd, 2011

 

In Part 3 we discussed validating techniques. Now in the final part of this series we will discuss how to validate the form as a whole.

How to Trigger Validation when the Form is Closing:

If you have worked with validation in the past, you may have noticed that the unfocused controls do not trigger validation when the form closes. To get around the issue, you can explicitly tell the form to validate its child controls and react accordingly.

A good place to trigger the validation is in the form’s FormClosing event:

$form1_FormClosing=[System.Windows.Forms.FormClosingEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.FormClosingEventArgs]
    #Validate only on OK Button
    if($form1.DialogResult -eq "OK")
    {
        #Validate the Child Control and Cancel if any fail
        $_.Cancel = -not $form1.ValidateChildren()    
    }
}

In the FormClosing event, we are checking if the user pressed the OK button, which has its DialogResult property set to “OK” (See PrimalForms 2011: Spotlight on the Button Control blog article for more details). By checking the DialogResult, we can bypass validation and allow the form to close when the user clicks on the cancel button or the X button in the upper right hand corner of the form’s window. Next we call the form’s ValidateChildren method which will trigger validation for all the controls contained in the form. The ValidateChildren method returns False if any of the controls fail validation. In the case where there is a validation failure, the $_.Cancel property is set to True and as a result prevents the form from closing.

Note: Preventing the form from closing is important when you are using multiple forms and are dependent on the returned data from the one form to be formatted correctly.

Handing Form Closing Validation without Canceling in the Validation event:

In the case where you are not setting the Validating $_.Cancel to True, which allows the control to lose focus, it is recommend to set a script scope variable that will flag when a control fails validation. The following is the modified Validation event for the control:

$textboxName_Validating=[System.ComponentModel.CancelEventHandler]{

    #Check if the Name field is empty
    $result = Validate-IsEmptyTrim $textboxName.Text    
    if($result -eq $true)
    {
        #Mark a failure only if the Validation failed
        $script:ValidationFailed = $true
        #Display an error message
        $errorprovider1.SetError($textboxName, "Please enter your name.");
    }
    else
    {
        #Clear the error message
        $errorprovider1.SetError($textboxName, "");
    }
}

The updated FormClosing event:

$form1_FormClosing=[System.Windows.Forms.FormClosingEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.FormClosingEventArgs]
    #Validate only on OK Button
    if($form1.DialogResult -eq "OK")
    {
        #Init the Validation Failed Variable
        $script:ValidationFailed = $false 
        #Validate the Child Control and Cancel if any fail
        $form1.ValidateChildren()    
        #Cancel if Validation Failed
        $_.Cancel = $script:ValidationFailed
    }
}

The updated FormClosing event initializes the $script:ValidationFailed variable to False. Any control that fails validation should set the variable to True, thus preventing the form from closing.

Helpful Validation Functions:

Finally, here are some common validation functions that you may find helpful:

function Validate-IsEmail ([string]$Email)
{
    return $Email -match "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|"+`
                        "[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))"+`
                        "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*"+`
                        "[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"
}

function Validate-IsURL ([string]$Url)
{
    if($Url -eq $null)
    {
        return $false    
    }
    
    return $Url -match "^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*"+`
                        "(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$"
}


function Validate-IsIP ([string] $IP)
{
    return $IP -match "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\."+`
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\."+`
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\."+`
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
}

function Validate-IsEmptyTrim ([string]$Text)
{
    if($text -eq $null -or $text.Trim().Length -eq 0)
    {
        return $true    
    }
    
    return $false
}

function Validate-IsEmpty ([string]$Text)
{
    return [string]::IsNullOrEmpty($Text)
}

function Validate-IsDate ([string]$Date)
{
    return [DateTime]::TryParse($Date,[ref](New-Object System.DateTime))    
}

[Note: These functions have been included as snippets since v2.0.13  service release]

You can download the Validation Sample Forms from our the Downloads section.

Validation-Sample-Form19

 

 
[Google+]   [Facebook]   [LinkedIn]   [StumbleUpon]   [Digg]   [Reddit]   [Google Bookmark]  

Tags: , , , ,