Infopath Validation Gotcha

30 December 2010

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 {
        this.Errors.Delete("MyErrorName");
    } catch (ArgumentException ex) { /* Error does not exist / has not been added. */ };

    if(MyErrorTest())
    {
        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...]

Tags: InfoPath, validation

Add a Comment

3 Comments

  • Taylor Lopez said Reply

    I realize that this is a LONG-dormant post, but here we go.

    I'm receiving the same error, however, I'm getting it when trying to set a field value on signature removal.

    Is the XML also put into a read only state under other circumstances?
    In this case, the user would be removing the signature through the built-in Digital Signature dialog box. I assumed I was receiving the error because the dialog box is modal, and is still open at the time of the signature removal code being triggered. Is there a way around this?

    Thank you

    • Henry said Reply

      Hey Taylor,

      I've lost most of my Infopath knowledge (having not touched it in quite a long time). The form is in a read-only state in the XmlEvent.Changing event as well as the Validating one mentioned, so if you're trying to set the value you should be doing so on the Changed event if you're not already doing so. That's about the extent that I remember, might be worth doing a poke around on MSDN as well - https://msdn.microsoft.com/en-us/library/office/microsoft.office.infopath.xmlevent.changing.aspx

      Best of luck!