We are going to explain an extra way to implement Form Field Validation Handlers in Alfresco.
We know the standard way is this, however if you are looking for another solution because the first one doesn’t satisfy your expectation, it’s your lucky day!
First, add a listener to control when the form is submited in a js file.
//Add a listener to control when the form is submitted document.body.addEventListener("submit", function (event) { //If there are wrong values if(wrongValues()){ //Cancel the event event.stopPropagation(); event.preventDefault(); } }, true);
Now, you can cancel the submit when you need it.
Second , show the error message.
We are going to implement a solution similar to Alfresco’s behavior.
To add a red background, like this
Add this line to the previous code (obviously, you can use CSS).
//Add a listener to control when the form is submited document.body.addEventListener("submit",function(event){ //If there are wrong values if(wrongProjects.length>0){ //Cancel the event event.stopPropagation(); event.preventDefault(); //Draw the background red $(ID_FIELD).css("background-color", "#faecee"); } }, true);
and to show a message to inform the issue when the field is focus, add the following lines:
To show the message when the field gains focus.
//When focus: Show a balloon tooltip //and set red color if there are wrong values $(ID_FIELD).on('focus', function (event) { var tooltip=_getBallonTooltip(); //If the field it's wrong if(wrongValues()){ //Set the message tooltip.html("Error message"); //Show the information tooltip.show(); //Set the background to red $(ID_FIELD).css("background-color","#faecee"); } });
To hide the message when the user leaves the input field
//When the user is typing, //hide a message and set the backgroud white $(ID_FIELD).on('keypress', function (event) { var tooltip=_getBallonTooltip(); $(ID_FIELD).css("background-color", "white"); tooltip.hide(); });
And finally, we have to implement the method to get the tooltip ballon.
var _getBallonTooltip=function(){ //If the var ballonValidate doesn't exist if(!ballonValidate) ballonValidate=Alfresco.util.createBalloon( "com-navycoms-installation", { width : "30em" }); return ballonValidateInstallation; }