Wednesday, October 17, 2012

Validate a field when its value changes

Problem: You have a text box control on an InfoPath form and want to display an error to the user if the text the user types into the text box is longer than 10 characters.

You can use the ReportError() method of the XmlValidatingEventArgs object or the Errors property of the form to display an error message to the user validating a field.

To validate a field when its value changes:

1 - Create a new form template and a Text Box control to it

2 - Add an event handler for the Validating event of the text box control

3 - If you want to use the ReportError() method to display the error message add the following code below:


          Dim fieldVal As String = e.Site.Value
            If Not String.IsNullOrEmpty(fieldVal) Then
                If fieldVal.Length > 10 Then
                    e.ReportError(e.Site, False, "Only 10 characters max allowed.")
                End If
            End If

or if you want to use the Errors() property of the form to display an error message:


Dim err As FormError() = Me.Errors.GetErrors("MaxCharError")
            If err IsNot Nothing Then
                If err.Length > 0 Then
                    Me.Errors.Delete("MaxCharError")
                End If
            End If

            Dim fieldVal As String = e.Site.Value
            If Not String.IsNullOrEmpty(fieldVal) Then
                If fieldVal.Length > 10 Then
                    Me.Errors.Add(e.Site, "MaxCharError", "Only 10 characters max allowed.")
                End If
            End If

4 - Save and preview the form

While the behavior of the two methods for displaying an error message to a user are similar, they differ in that the ReportError() method adds a SystemGenerated error to the FormErrorCollection object of the form, while the Add() method adds a UserDefined error to the FormErrorCollection object of the form.

No comments:

Post a Comment

About Me

My photo
Toronto, Ontario, Canada
MBA, M.Sc. & MCP