jeffchannell.com

Validate Custom Administrator Form

Posted in Joomla!
2009-08-10 20:20:08 +0000 UTC

I've been working on a custom Joomla component for a client at work, and needed to validate that certain aspects of the admin form. I could have recreated the wheel and written my own validation routine, but I really wanted to use Joomla's core validation behavior. What follows is how I managed to validate a form when submitted using the core Joomla toolbar buttons.

The first thing I did was add the form validation behavior into my view, as this is not loaded by default:

JHTML::_( 'behavior.formvalidation' );

I added this one liner to both the displayEdit and displayAdd functions in my form's view. The next step was to add the necessary items to my form. In the view's template, I changed my form tag to have a specific class and submit function:

<form action="index.php" method="post" name="adminForm" id="adminForm" class="form-validate" onsubmit="return doValidate( this );">

Then, on each input/textarea that I wanted to validate, I added the class "required", as well as any specific validation classes available (see here for all the classes available).

Finally, I added the following to the bottom of the view's template. Basically, I was having an issue where the toolbar buttons would fire the onsubmit event, but ignore the return value and submit the form. What I ended up doing was creating my own JFormValidator by extending the original with nothing and overriding the core 'submitbutton' JavaScript function. I also appended a CSS style tag to handle invalid inputs (I could have added these to the administrator template, but I wanted to make sure this change survived a reinstall/upgrade).

<script type="text/javascript">
  // thanks to epsi for pointing me in the right direction!
  // http://forum.joomla.org/viewtopic.php?f=304&t=419618
  
  // "extend" base validator
  var myFormValidator = JFormValidator.extend({});
  // override core behavior
  function submitbutton( pressbutton )
  {
    if( pressbutton == 'cancel' )
    {
      submitform( pressbutton );
      return true;
    }
    var form = document.adminForm;
    var validator = new myFormValidator();
    if( validator.isValid( form ) )
    {
      submitform( pressbutton );
    }
    else
    {
      alert( 'Please correct any errors before submission.' );
    }
  }
  // our validation script
  function doValidate( f )
  {
    if( document.formvalidator.isValid( f ) )
    {
      return true;
    }
    return false;
  }
</script>
<style type="text/css">
  .invalid { border: 1px solid red; }
</style>

One caveat I should mention is that this override does indeed ignore the 'cancel' button, thus allowing the form to be canceled using the toolbar 'Cancel' button, which is something not taken into account in the original snippet I found on the Joomla forums.