LOGIC Library

This site is the Logic involvement in sharing expertise and skills acquired in daily work. The goal is to create a solid knowledge base and share best practices in software development and systems management.

More info about us can be found on logicsistemi.it.

Joomla! 2.5 form validation - part 1

In the Joomla! MVC tutorial I wrote a post related to form validation. The instructions given in that post were built on the base of the MVC pattern. Using Joomla! validation system to validate a standard form written in HTML requires some better explanation.

In this tutorial I try to take a deep look into the Joomla! validation code, client and server side, using it in a standard module composed by an HTML form and the PHP code to manage required data.

The base module

To explain form validation we need an HTML form and some PHP code that read user input and validate it server side. The easiest way to realize this in Joomla! is by creating a very simple module that display an HTML form and elaborates submitted values.

To simplify the code our module will be composed by a single PHP file. To translate the module into something that could be released, we need, at least, to:

  • separate the elaboration of the user input from the HTML form display by using a template
  • using the token to improve security
  • add internationalization support

but this is beyond the scope of this tutorial.

Let's start by creating a folder on your pc with the following structure:

com_validatedform
  mod_validatedform.xml
  mod_validatedform.php
  index.html

Index.html is an empty file used to hide folder content and mod_validatedform.xml is a minimal manifest file for our module with the following content:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="2.5.0" client="site" method="install">
    <name>Validated form</name>
    <author>Edy Incoletti</author>
    <authorEmail>edy.incoletti@logicsistemi.it</authorEmail>
    <authorUrl>eincoletti.wordpress.com</authorUrl>
    <creationDate>October 2012</creationDate>
    <version>1.0.0</version>
    <description>A simple form with standard Joomla! validation.</description>     <files>
        <filename module="mod_validatedform">mod_validatedform.php</filename>
        <filename>index.html</filename>
    </files>
</extension>

 The mod_validatedform.php is where we will write our code, so let's open it and create a simple form:

<?php
defined ( '_JEXEC' ) or die ( 'Restricted access' );

$msg = "";
$msg_class = "";
if ($_REQUEST["validatedform"] == "submit") {
$msg_class = "message";
$msg = "Data saved!";
}

if ($msg_class != "") {
?>
<div id="system-message-container">
<dl id="system-message">
<dd class="<?=$msg_class?> message">
<ul>
<li><?=$msg?></li>
</ul>
</dd>
</dl>
</div>
<? } ?>
<form method="post" action="<?=$_SERVER["REQUEST_URI"]?>">
<input type="hidden" value="submit" name="validatedform" />
<fieldset>
<legend>Validated form</legend>
<dl>
<dt>
<label for="jform_name">Name:</label>
</dt>
<dd>
<input type="text" size="30" value="" id="jform_name" name="jform[name]" />
</dd>
<dt>
<label for="jform_email" id="jform_email-lbl">E-mail:</label>
</dt>
<dd>
<input type="text" size="30" value="" id="jform_email" name="jform[email]" />
</dd>
<dt>
<label for="jform_amount" id="jform_amount-lbl">Amount:</label>
</dt>
<dd>
<input type="text" size="30" value="" id="jform_amount" name="jform[amount]" />
</dd>
</dl>
</fieldset>
<div>
<button type="submit">Save data</button>
</div>
</form>

This form display some fields inside a fieldset tag and a submit button. Input controls are completed by an hidden field used to recognize the submit action.

At this moment, when the submit happen we simply see a message that confirm submission. Our final example will do not much more than this: the submission will be confirmed if the form validation will be right, or the validation error will be displayed.

Fields names are set accordingly to Joomla! convention used in MVC components.

Joomla! validation libraries

Joomla! 2.5 offer 2 different approaches to form validation:

  • Client side validation using Mootools
  • Server side validation using PHP libraries

The methods are designed to work togheter to get the best of both. Client side validation offer immediate user feedback, but can be easily outflanked disabling Javascript support on the browser. Server side validation is slower, but can perform validation using information that come from other sources, such as other data stored on the server (i.e. can check if a selected username is already present in the system).

Client side validation

To activate client side validation we need to perform the following tasks:

  • Load required Javascript libraries
  • Set the class "form-validate" on the form that should be validated
  • Set the validation classes on the input fields

The first item requires to add the file /media/system/js/validate.js to our page. This can be done using Joomla! libraries with the following instruction:

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

 Then we can modify the form tag by adding the right class:

<form method="post" action="<?=$_SERVER["REQUEST_URI"]?>" class="form-validate">

Then we can add specific class to validate input field using some predefined methods. Joomla! seems not support all the validators defined in the Mootols documentation: http://mootools.net/docs/more/Forms/Form.Validator#Validators, but only the following classes:

  • required
  • validate-username
  • validate-password
  • validate-numeric
  • validate-email
  • validate-[custom]

We will come back next on the custom values and, for now, we limit our example to some standard validation method. Let's modify our input fields in the following way:

<input type="text" size="30" value="" id="jform_name" name="jform[name]" class="required" />
<input type="text" size="30" value="" id="jform_email" name="jform[email]" class="validate-email" />
<input type="text" size="30" value="" id="jform_amount" name="jform[amount]" class="validate-numeric" />

To create an installable module and try it on our Joomla! site we have to compress our folder and install the module using Joomla! extension manager. The module can then be added to any position in our page. In a production environment it's common to load module in the main section of the page using the loadmodule or loadposition directives.

We can try the example and notice that:

  • On field blur, if field is invalid is label is changed (usually in red, but it depends from the template you are using and the CSS attributes sets for the "invalid" class)
  • In some cases (required field and e-mail) a tooltip showing the problem is displayed
  • On submit, required fields and e-mail format are blocking
  • Some kind of validation, such as numeric, are not blocking

We complete the example with a script and a modification to the form tag to avoid insert when validation fail:

<script language="javascript">
function myValidate(f) {
   if (document.formvalidator.isValid(f)) {
      return true;
   }
   else {
      var msg = 'Some values are not acceptable.  Please retry.';
 
      alert(msg);
   }
   return false;
}
</script>


<form method="post" action="<?=$_SERVER["REQUEST_URI"]?>" class="form-validate" onSubmit="return myValidate(this);">

Our client side validation is now working and can be tested.

In the next post we will take a look to the server side validation.

Comments   

 
#1 pragya sharma 2013-07-12 11:36
thanks Edy

with some changes i have implemented validations in my form. now i m going to implement sever side validations.
Quote
 
 
#2 patrick 2014-02-19 16:50
Hi. I have implemented things as you said. But the last part isnt working. I can't get myValidation to get working.
Where do I have to declare it?

If I use window.addEvent ("domready, function()..., it only loads when page loads and then doesnt work.
Quote
 
 
#3 Edy Incoletti 2014-02-20 08:59
Quoting patrick:
Hi. I have implemented things as you said. But the last part isnt working. I can't get myValidation to get working.
Where do I have to declare it?

If I use window.addEvent("domready, function()..., it only loads when page loads and then doesnt work.

Hi, myValidation function is called by the onsubmit event of the form (look at the form tag parameters), so it's automatically called when you press the submit button.
If it doesn't work, look if there is any error in the JS or try to write the onSubmit attribute in lowercase.
Quote
 
 
#4 patrick 2014-02-20 11:20
Thank you so much for your time :).
I get it to work, but the function blows up at the:
if (document.formva lidator.isValid(form))
line.
I have add custom validation rules successfully, so the document.formva lidator variable is initialized.
Quote
 
 
#5 patrick 2014-02-20 12:25
I found a way around! Make your myValidate function like mine and you are good to go. It detects any invalid entries, numeric, custom, ...


function my_validate(for m) {

var valid = true;

// Validate form fields
var elements = form.getElement s('fieldset').c oncat(Array.fro m(form.elements ));
for (var i=0;i < elements.length ; i++) {
if (document.formv alidator.valida te(elements) == false) {
valid = false;
}
}

// Run custom form validators if present
new Hash(document.f ormvalidator.cu stom).each(func tion(validator) {
if (validator.exec () != true) {
valid = false;
}
});

return valid;
}

function validate_form(f orm) {

if (my_validate(for m)) {
return true;
}
else {
alert("Bitte füllen Sie das Formular follständig und fehlerfrei aus.");
return false;
}
}
Quote
 
 
#6 Edy Incoletti 2014-02-20 16:12
Quoting patrick:
Thank you so much for your time :).
I get it to work, but the function blows up at the:
if (document.formvalidator.isValid(form))
line.
I have add custom validation rules successfully, so the document.formvalidator variable is initialized.

Have you add the following line?
JHtml::_('behavior.formvalidation');
This includes the JS libraries needed to perform the validation.
Check your HTML output.
Quote
 

Add comment


Security code
Refresh