Form Validation with MooTools

  • PDF

To extend out forms even further we can utilize the Mootools java script that comes with Joomla.

Mootools.js has built in routines for validating numerics, emails and other common form validation examples.  Custom validation can also be added quite easily.

First we want to add the validation code to our form:

<?php JHTML::_('behavior.formvalidation'); ?>
 
<script language="javascript">
function myValidate(f) {
   if (document.formvalidator.isValid(f)) {
      f.check.value='<?php echo JUtility::getToken(); ?>'; //send token
      return true; 
   }
   else {
      var msg = 'Some values are not acceptable.  Please retry.';
 
      //Example on how to test specific fields
      if($('email').hasClass('invalid')){msg += '\n\n\t* Invalid E-Mail Address';}
 
      alert(msg);
   }
   return false;
}
</script>
 
<h1>Guestbook Entry form</h1>
 
<form id="form1" name="form1" method="post"
     class="form-validate" onSubmit="return myValidate(this);"
     action="index.php?option=com_guestbook&task=add">
 
    <input type="hidden" name="check" value="post"/>
  <p>Enter message here:<br /> 
    <textarea name="message" cols="60" rows="4" id="message"></textarea>
  </p>
  <p>
    <label>Email: </label>
    <input name="email" type="text" id="email"  class="required validate-email"/>
  </p>
<?php echo JHTML::_('form.token'); ?>
  <p>
  <input type="submit" name="Submit" value="Post Entry" />
  </p>
</form>
 
<?php     } ?>
 

Then we have to check that the validation has been completed, using the token we set earlier:

    case 'add': 
         // Check that the form has been validated.
         JRequest::checkToken() or jexit('Invalid Token');
               addEntry(); 
               break; 

The for a last touch we add this to our css, to indicate a failed validation:

.invalid {color:red;}

This will give us a nifty way to validate our fields.

So in our example above the email field is both a required field and is also going to be validated using the built in validation mask 'validate-email'.  If our email field is not entered or has an invalid email format, the Mootools validator will set the class for that field to invalid - our form field will then have a red outline from our simple css above and the field will be detected in our JavaScript.  An alert box with the comment 'Invalid E-Mail Address' will be displayed to our user.

Exercise in class:

> Re-write so that the message field is required.

> Add a new field that has to be a numeric.

For more complicated validation you can create a custom validation script, using regex, in this manner:

Window.onDomReady(function(){
   document.formvalidator.setHandler('birth', function(value) {
      regex=/^\d{4}(-\d{2}){2}$/;
      return regex.test(value);
   })
})

The background for this tutorial comes from the Joomla Documentation located at this link:

http://docs.joomla.org/Form_validation