Henry Chong

Infopath Validation Gotcha

Man Explaining Things from Laptop To Woman Looking Confused

📷: Gustavo Fring

In an InfoPath form I've been working on, I've used the Validating event to attach some code to do some more complex validation (ie, something that I can't achieve through rules). It's actually not too complicated, and follows the following general syntax:

public void MyField_Validating(object sender, XmlValidatingEventArgs e)
//clear any existing errors
try {
} catch (ArgumentException ex) { /* Error does not exist / has not been added. */ };
this.Errors.Add(e.Site, "NoEmailsFound", "My error message.");

However, it's important to note that during the Validating event the underlying form XML data is placed into a read-only state. This means that if you try and update a "notification" or "errormessage" field as part of a Validating event handler like I was, you will encounter an "InvalidOperationException: Operation is not valid due to the current state of the object". The MSDN reference on the XmlEvent.Validating event also mentions this somewhere on the page.

Hope you've all had a fantastic Christmas, and are looking forward to an exciting new year!

[Edit: I've been having trouble getting the red border to appear when using e.ReportError / this.Errors.Add() for a People Picker control; the validation works as expected as submission is disabled and Ctrl+Shift+I brings up the validation error message, but there is no visual indicator for the error, which is rather annoying. This thread was the only thing I could find about this error, but isn't particularly helpful as it suggests using design-time rules which I would use instead of code-behind, if it were possible...]