Thursday, November 22, 2012

Clear a specific validation error in a form

Problem: You want to be able to clear a specific error in a form.

You can use the Delete() method of the Errors collection to clear a specific error in a form by passing either a name or a FormError object to the method.

To clear a specific error in a form by name:

1 - Create a new form template and add a Text Box control. Name the control field1

2 - Add the following code to the event handler for the Validating event of the text box field 1

                If e.Site IsNot Nothing Then
                If e.Site.Value.Length > 10 Then
                    Errors.Add(e.Site, "MaxCharsErr", "Only 10 characters max allowed.")
                End If
            End If

This code checks whether the amount of characters typed into the text box exceeds 10 and if it does it adds a user-defined error named MaxCharsErr to the Errors collection of the form.

3 - Add a second Text Box control to the form and call it "Required". Make this field required by selecting its Cannot be Blank property. The purpose of this text box is to add a schema validation error to the Errors collection of the form, so that there is more than one error in the collection for testing purposes.

3 - Add a Button to the form. Add the following code to the Clicked event of the button

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

The first line of code retrieves all of the errors that have the name MaxCharsErr from the Errors collection. The second and third lines of code check whether any FormError objects were returned by the GetErrors() method, and if so, the Delete() method is called to delete them.

4 - Save and Preview the form

When the form opens, a red asterisk (*) should appear in the required text box as an indication that it is a required field. Enter a piece of text that is longer than 10 characters in the field1 text box. A red dashed border should appear around the text box. Click the button and the red dashed border should disappear  but the asterisks in the required text box should still be present. With this you have cleared the validation error on the field1 text box, not not on the required text box.

About Me

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