Showing custom bootstrap error message on Joomla 3.x administration

Today while developing my Joomla component I was told to show custom error message while doing javascript validation at admin side.

Based on the Joomla documentation you can set a field as required as below.

<field name="totalsms" 
 label="Sample Admin Field"
 required="true" />

The above field will be automatically validated at admin side if the form is submitted without giving a value in it.

However my requirement was to validate a field’s value based on another field’s value.  In my admin form I have 2 fields named as ‘Need Book’ and ‘Which Book’.  Need book is a list button where Yes or No will be displayed.  If the admin selected ‘Yes’ then the next field Which Book should be validated for mandatory.

Here is what I did today.  Definitely there would be better ways to do.

In Joomla admin, the error messages are displayed as below.


These error messages are displayed under a div container ‘system-message-container’.  My idea is to hack this div container and show my custom error message.

Below are the javascript methods I introduced

This javascript method will create a new div container with the provided message and add them inside system-message-container.

function addCustomMessage(message, uniqid, css){
 css = typeof css !== 'undefined' ? css : '';
 var errcontainer = document.getElementById('system-message-container');
 var pnode = document.createElement("p");
 var textnode = document.createTextNode(message);
 var divnode = document.createElement("div");
 var already_available = document.getElementById(uniqid);
 if(already_available) return;
 divnode.className = "alert "+css;

This javascript method is to delete the newly created div container

function removeCustomMessage(uniqid){
 var parent = document.getElementById("system-message-container");
 var child = document.getElementById(uniqid);

Below is the javascipt code which does the validation in my default.php

if(document.getElementById('jform_need_book').value == 'YES' && document.getElementById('jform_which_book').value == ''){
  addCustomMessage("Please select a book", 'val_select_book', 'alert-error');

Thats all.

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *