Display error messages inside labels

By default, the TMT validator uses JavaScript alert boxes to display errors to the user. If you want to display errors in a custom, or more user friendly way, we can take advantage of it's extensibility.

First, we must attach a tmt:callback attribute to the <form> tag:

<form action="index.htm" method="post" tmt:validate="true" tmt:callback="errorOnLabels">

The validator will invoke a JavaScript function based on the value of the tmt:callback attribute (errorOnLabels in this case).

This example shows error messages displayed as the field's label. This solves the issue of error messages not being listed by the validator in the order in which they appear on the page layout, as each error message is displayed next to the relevant field.

The JavaScript code is somewhat more complex than other custom solutions, but it's fully reusable

function errorOnLabels(formNode, validators){
 var labelNodes = formNode.getElementsByTagName("label");
 // Reset all the labels
 resetLabels(labelNodes);
 for(var i=0; i<validators.length; i++){
  var label = getLinkedLabel(labelNodes, validators[i].name);
  if(label){
   // Flag the labels
   flagLabel(label, validators[i].message);
  }
 }
}

function getLinkedLabel(labelNodes, fieldID){
 for(var i=0; i<labelNodes.length; i++){
  if(labelNodes[i].htmlFor == fieldID){
   return labelNodes[i];
  }
 }
}

function flagLabel(labelNode, message){
 labelNode.oldText = labelNode.firstChild;
 var strongNode = document.createElement("strong");
 var textNode = document.createTextNode(message);
 strongNode.appendChild(textNode);
 labelNode.replaceChild(strongNode, labelNode.firstChild);
}

function resetLabels(labelNodes){
 for(var i=0; i<labelNodes.length; i++){
  if(labelNodes[i].oldText){
   labelNodes[i].replaceChild(labelNodes[i].oldText, labelNodes[i].firstChild);
  }
 }
}

Generic Form