Reg Exp
Web Design
Notes Client
Adding text before a group of error messages
On a recent project, I was having a lot of fields to validate. Instead of the user going through one error message, fix, resubmit, next error message, and so on, I decided it would be good to include all the error messages at once. Basically, I was going to be using <xp:messages></xp:messages> instead of <xp:message for="someField"></xp:message>.

What I wanted to happen was to put some block of text above the list of error messages. Something telling the user "this is the reason (or these are the reasons) why the document wasn't saved". I tried updating the list of errors when I first encountered an error (I was using SSJS to do all the validation), but sometimes the error message would show up at the top of the list, sometimes as the bottom, and sometimes in the middle. I wanted it to show up at the top without fail. I came up with a way to do it pretty elegantly.

For the XPage event "onClientLoad", I added some client-side JavaScript code to look for an error block and update it. Here's the XPage source, with the actual JavaScript removed:

<xp:eventHandler event="onClientLoad" submit="false">
     <xp:this.script><![CDATA[.... javascript code.... ]]></xp:this.script>

And here is the JavaScript that goes into the "onClientLoad" event:

var errorBlock = document.getElementsByClassName("xspMessage");
if (errorBlock) {
   if (errorBlock.length > 0) {
      var e = errorBlock[0];
      var n = document.createElement("B");
      var t = document.createTextNode("The following fields are required before the document can be saved:");
      e.insertBefore(n, e.childNodes[0]);

The JavaScript finds an element with the class of "xspMessage". This is the indicator that there is an error message block. If you put your own styling on the <xp:messages> tag, then you'll need to use the same class name in the JavaScript code. If there is an error block found, then get the first one (at the top of the page). Create a new element with bold styling ("B") and put some constant text inside that element. Then insert that new element before the first child node with the "xspMessage" style. The first child node is a <UL> node, so this bold text will appear before the list of field(s) that had an error and won't break the HTML rules.