By default the validator uses JavaScript alert boxes to display errors to the user. If we want to display errors in a custom, more user friendly way, we can take advantage of extensibility.
First of all we must attach a tmt:callback attribute to the <form> tag:
<form action="index.htm" method="post" tmt:validate="true" tmt:callback="displayError">
The validator will invoke a JavaScript function based on the value of the tmt:callback attribute (displayError in this case).
Now we need to write the JavaScript function like this:
<script type="text/javascript">
function displayError(formNode, validators){
// Your custom code goes here
}
</script>
The validator will pass two arguments to our custom JavaScript code:
We can iterate over the validators array (using a for loop) and, for each validator object, refer to its name and message properties. A very crude example will look more or less like this:
function displayError(formNode, validators){
var errorHTML = "";
for(var i=0;i<validators.length;i++){
errorHTML += "<li><em>" + validators[i].name + "</em>: " + validators[i].message + "</li>";
}
document.getElementById("errorDisplay").style.display = "block";
document.getElementById("errorDisplay").innerHTML = "<ul>" + errorHTML + "</ul>";
}
In this case we concatenate the name and message properties to form a string of XHTML code that will be displayed inside a <div> tag just above the form.
The script above is a simple, easy to understand and quite effective solution, still, is far from being ideal. First of all, it requires to hardcode the error display area inside your XHTML; then, since the id of the area is hardcoded inside the function, you can’t validate more than one form for each page. A more generic, fully reusable solution would require some additional code that is outside the scope of this documentation. If you would like to use an out of the box solution, see errorBoxCallback.
Please note the callback function gets invoked even if the form doesn't contain errors. In this case the "validators" argument contains an empty array. This way it can reset error display and clean-up the GUI. This is especially important for forms that get submitted using Ajax, without refreshing the page.
Kyosuke Takayama wrote an interesting extension to TMT Validator for custom error display. It's called Baloon Error and it's definitely worth a look