Infragistics(R) NetAdvantage(R) Windows Forms
ValidationError Event
See Also  Example E-mail your feedback on this topic.
Infragistics.Win.Misc Namespace > UltraValidator Class : ValidationError Event

Occurs when the validation of a control or embeddable editor fails.

Syntax

Visual Basic (Declaration) 
Public Event ValidationError As ValidationErrorHandler
C# 
public event ValidationErrorHandler ValidationError

Event Data

The event handler receives an argument of type ValidationErrorEventArgs containing data related to this event. The following ValidationErrorEventArgs properties provide information specific to this event.

PropertyDescription
Control Returns the control whose value failed validation, or null if the validation entity is not a control, or more than one control was validated. Applicable only when IsSingleEntityValidation returns true.
Editor Returns the Editor whose value failed validation, or null if the validation entity is not an embeddable editor. Applicable only when IsSingleEntityValidation returns true.
IsSingleEntityValidation Returns whether this instance represents the validation of a single control or embeddable editor.
NotificationSettings Returns a NotificationSettings instance which exposes properties that enable customization of the manner in which the end user is notified of the validation error.
Validation Returns the Validation instance which contains information about the validation(s) that caused the error.

Example

The following code sample demonstrates how to use the properties of the ValidationSettings object to ensure that the value entered intoa TextBox conforms to a string pattern such as a phone number or postal code, and how to use the ValidationError event to customize the error message that is displayed to the end user when a validation fails:

For an overview of how to handle events in Visual Basic or Visual C#, see Event Handlers in Visual Basic and Visual C#. For specific information and code examples illustrating how to consume events in your application, see Consuming Events in the .NET Framework Developer's Guide.

Visual BasicCopy Code
Imports Infragistics.Win
Imports Infragistics.Win.Misc
Imports System.Drawing
Imports System.Drawing.Drawing2D

    Private Const USPhonePatternLong As String = "^\(\d{3}\) \d{3}-\d{4}$"
    Private Const USPhonePatternShort As String = "^\d{3}-\d{4}$"
    Private Const USPostalCodeLong As String = "^\d{5}-\d{4}$"
    Private Const USPostalCodeShort As String = "^\d{5}$"
    Private Const USSocialSecurityNumber As String = "^\d{3}-\d{2}-\d{4}$"
    Private Const EMailPattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9][a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"

    Private Enum ValidationPattern
        EmailAddress
        USPhoneLong
        USPhoneShort
        USPostalCodeLong
        USPostalCodeShort
        USSocialSecurityNumber
    End Enum

    Private Sub AssignPattern(ByVal ultraValidator As UltraValidator, _
                                ByVal textBox As TextBox, _
                                ByVal pattern As ValidationPattern, _
                                ByVal retainFocusOnError As Boolean)

        '  Get the appropriate Regex pattern to use
        Dim regexPattern As String = String.Empty

        Select Case pattern

            Case ValidationPattern.EmailAddress
                regexPattern = EMailPattern
            Case ValidationPattern.USPhoneLong
                regexPattern = USPhonePatternLong
            Case ValidationPattern.USPhoneShort
                regexPattern = USPhonePatternShort
            Case ValidationPattern.USPostalCodeLong
                regexPattern = USPostalCodeLong
            Case ValidationPattern.USPostalCodeShort
                regexPattern = USPostalCodeShort
            Case ValidationPattern.USSocialSecurityNumber
                regexPattern = USSocialSecurityNumber

        End Select

        '  Get a ValidationSettings instance to be associated with the
        '  specified control. Note that the GetValidationSettings will
        '  create an instance and assign it automatically if the control
        '  is not already associated with an instance.
        Dim validationSettings As ValidationSettings = ultraValidator.GetValidationSettings(textBox)

        '  Create an OperatorCondition instance for Regex validation, using the
        '  specified pattern, and assign it to the ValidationSettings' Condition property.
        validationSettings.Condition = New OperatorCondition(ConditionOperator.Match, regexPattern)

        '  Require that the field not be left empty, and specify what the validator
        '  should consider to constitute an empty value.
        validationSettings.IsRequired = True
        validationSettings.EmptyValueCriteria = EmptyValueCriteria.NullOrEmptyString

        '  Specify which property of the TextBox should be used to obtain
        '  the value to be validated.
        validationSettings.ValidationPropertyName = "Text"

        '  Set the RetainFocusOnError property according to the caller's specifications.
        validationSettings.RetainFocusOnError = retainFocusOnError

        '  Use the NotificationSettings to make a MessageBox appear when a validation
        '  fails, and customize the caption for the MessageBox.
        validationSettings.NotificationSettings.Action = NotificationAction.MessageBox
        validationSettings.NotificationSettings.Caption = "Invalid String Pattern"

        '  Use the Tag property to store the pattern.
        validationSettings.Tag = pattern

        '  Handle the UltraValidator's ValidationError event so we can customize
        '  the notifications.
        AddHandler ultraValidator.ValidationError, AddressOf Me.OnPatternValidationError
    End Sub


    '  Handles the UltraValidator's ValidationError event for Regex pattern validations
    Private Sub OnPatternValidationError(ByVal sender As Object, ByVal e As ValidationErrorEventArgs)

        '  Get a reference to the Validation object under which the information
        '  about the validation error appears.
        Dim validation As Validation = e.Validation

        '  Return if this is a programmatic validation
        If validation.Trigger = ValidationTrigger.Programmatic Then Return

        '  Get a reference to the ValidationResult object which describes
        '  the reason for failure
        Dim result As ValidationResult = validation.Errors(0)

        '  Get the value which caused the validation to fail, so we can include
        '  it in the message that is displayed to the end user.
        Dim text As String = result.Value

        '  Get a reference to the ValidationSettings object which was used
        '  to determine that the value is invalid.
        Dim validationSettings As ValidationSettings = result.ValidationSettings

        '  Get a reference to the NotificationSettings object which determines
        '  how the end user will be notified. For single-entity validations, we
        '  can set the properties of this instance, so that the notification
        '  behavior can be customized dynamically.
        Dim notificationSettings As NotificationSettings = e.NotificationSettings

        '  Customize the error message that is displayed to the end user.
        notificationSettings.Text = String.Format("The value '{0}' for field '{1}' does not conform to the '{2}' pattern.", Text, ValidationSettings.Control.Name, ValidationSettings.Tag)
    End Sub
C#Copy Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.Misc;
using System.Drawing;
using System.Drawing.Drawing2D;

    private const string USPhonePatternLong = @"^\(\d{3}\) \d{3}-\d{4}$";
    private const string USPhonePatternShort = @"^\d{3}-\d{4}$";
    private const string USPostalCodeLong = @"^\d{5}-\d{4}$";
    private const string USPostalCodeShort = @"^\d{5}$";
    private const string USSocialSecurityNumber = @"^\d{3}-\d{2}-\d{4}$";
    private const string EMailPattern = @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";

    private enum ValidationPattern
    {
        EmailAddress,
        USPhoneLong,
        USPhoneShort,
        USPostalCodeLong,
        USPostalCodeShort,
        USSocialSecurityNumber,
    }

    private void AssignPattern( UltraValidator ultraValidator,
                                TextBox textBox,
                                ValidationPattern pattern,
                                bool retainFocusOnError )
    {
        //  Get the appropriate Regex pattern to use
        string regexPattern = string.Empty;

        switch ( pattern )
        {
            case ValidationPattern.EmailAddress:
            {
                regexPattern = EMailPattern;
            }
            break;

            case ValidationPattern.USPhoneLong:
            {
                regexPattern = USPhonePatternLong;
            }
            break;

            case ValidationPattern.USPhoneShort:
            {
                regexPattern = USPhonePatternShort;
            }
            break;

            case ValidationPattern.USPostalCodeLong:
            {
                regexPattern = USPostalCodeLong;
            }
            break;

            case ValidationPattern.USPostalCodeShort:
            {
                regexPattern = USPostalCodeShort;
            }
            break;

            case ValidationPattern.USSocialSecurityNumber:
            {
                regexPattern = USSocialSecurityNumber;
            }
            break;
        }

        //  Get a ValidationSettings instance to be associated with the
        //  specified control. Note that the GetValidationSettings will
        //  create an instance and assign it automatically if the control
        //  is not already associated with an instance.
        ValidationSettings validationSettings = ultraValidator.GetValidationSettings( textBox );

        //  Create an OperatorCondition instance for Regex validation, using the
        //  specified pattern, and assign it to the ValidationSettings' Condition property.
        validationSettings.Condition = new OperatorCondition( ConditionOperator.Match, regexPattern );

        //  Require that the field not be left empty, and specify what the validator
        //  should consider to constitute an empty value.
        validationSettings.IsRequired = true;
        validationSettings.EmptyValueCriteria = EmptyValueCriteria.NullOrEmptyString;

        //  Specify which property of the TextBox should be used to obtain
        //  the value to be validated.
        validationSettings.ValidationPropertyName = "Text";

        //  Set the RetainFocusOnError property according to the caller's specifications.
        validationSettings.RetainFocusOnError = retainFocusOnError;

        //  Use the NotificationSettings to make a MessageBox appear when a validation
        //  fails, and customize the caption for the MessageBox.
        validationSettings.NotificationSettings.Action = NotificationAction.MessageBox;
        validationSettings.NotificationSettings.Caption = "Invalid String Pattern";

        //  Use the Tag property to store the pattern.
        validationSettings.Tag = pattern;

        //  Handle the UltraValidator's ValidationError event so we can customize
        //  the notifications.
        ultraValidator.ValidationError += new ValidationErrorHandler( this.OnPatternValidationError );
    }

    //  Handles the UltraValidator's ValidationError event for Regex pattern validations
    private void OnPatternValidationError( object sender, ValidationErrorEventArgs e )
    {
        //  Get a reference to the Validation object under which the information
        //  about the validation error appears.
        Validation validation = e.Validation;

        //  Return if this is a programmatic validation
        if ( validation.Trigger == ValidationTrigger.Programmatic )
            return;

        //  Get a reference to the ValidationResult object which describes
        //  the reason for failure
        ValidationResult result = validation.Errors[0];

        //  Get the value which caused the validation to fail, so we can include
        //  it in the message that is displayed to the end user.
        string text = result.Value as string;

        //  Get a reference to the ValidationSettings object which was used
        //  to determine that the value is invalid.
        ValidationSettings validationSettings = result.ValidationSettings;

        //  Get a reference to the NotificationSettings object which determines
        //  how the end user will be notified. For single-entity validations, we
        //  can set the properties of this instance, so that the notification
        //  behavior can be customized dynamically.
        NotificationSettings notificationSettings = e.NotificationSettings;

        //  Customize the error message that is displayed to the end user.
        notificationSettings.Text = string.Format( "The value '{0}' for field '{1}' does not conform to the '{2}' pattern.", text, validationSettings.Control.Name, validationSettings.Tag );
    }

Remarks

When a validation session yields one or more failures, the ValidationError event is fired. The event arguments class exposes a NotificationSettings instance which contains resolved property values; these property values define the manner in which the end user will be notified of the failed validation. In the case where a single control/editor was validated (see IsSingleEntityValidation), these property values can be modified at will to customize the notification that is issued to the end user. The event arguments class also exposes a Validation property, which exposes two collections of Infragistics.Win.Misc.ValidationResult objects; the Results collection contains a ValidationResult for each validation regardless of whether it passed or failed, and the Errors collection contains a ValidationResult for each validation that failed. In the case where a single control/editor was validated, each of these collections will always contain only one member.

See Also