Wednesday, December 8, 2010

Using XmlFormHostItem.Errors for validation

When I first started out developing in InfoPath, I frequently used conditional formatting to satisfy business rules in forms. Did you not fill out the city field in your address? Can't hit the Submit button! It was effective, though not very workable with end users who wouldn't necessarily know what fields they missed. Furthermore, what if I was pre-loading data on initialization and the form was missing a hidden required field?

Now I use XmlFormHostItem.Errors, or simply Errors. Errors is FormErrorCollection object which contains all the FormError instances in your form, which includes both required fields that have not been filled in and also Data Validation failures. You can iterate over the errors and report them back to the user, dump them to trace/logging, whatever you want to do. I usually keep a hidden section which is tied to a boolean value in the main dataset and if the form submission fails to validate, the boolean is set to true and the note appears, advising the user to double-check the form for required fields.

You sometimes will have to get creative in handling some controls that don't support Data Validation. For example, a form I have been working on requires the user to provide at least one file attachment for documentation of a request. The file attachment control of course doesn't support Data Validation, nor does the Button control. In these cases, I'll put the control in a new section (provided it isn't in one already), manually apply a bright red asterisk in text adjacent to the control in one section, and use conditional formatting to show the section with the asterisk until the condition has been satisfied.

Ooh, are we using conditional formatting to handle business logic again? No matter - to go along with it, I'll create a new text field in the schema, insert that field in one of the two sections, and put the data validation on *that* field. Now I just have to use that control as a proxy for the validation. For example, once my code has handled the file attachment, I'll also set the value of this proxy field in code, and the data validation will be satisfied.

Simple and elegant, and also far easier to troubleshoot when issues arise.