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 user plugin: adding validation

In a previous post we have learned how to extend users' data with custom fields during a Joomla! user registration. In the example we have left the new fields without any validation.

In this post we will add 3 types of validation to the new fields: client side validation, server side validation and a complex server side validation.

To undestand every passage of this post I suggest you to read the Joomla! form validation tutorial and the last part of the Joomla! MVC component tutorial. They both have information about validation we will use in this example.

 

Client side validation

Client side validation is done using the Mootools library and is already integrated with the xml form definition we used to add the new fields.

Using Mootools we have the required attribute and the following fields validation:

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

So we can check that the field is a valid number or a valid email, but also we can add custom Javascript rules.

To add a standard validation rule we can simply modify the profiles/profile.xml file in the following way:

<?xml version="1.0" encoding="utf-8"?> 
<form> 
	<fields name="testprofile"> 
		<fieldset name="testprofile" 
			label="PLG_USER_TESTPROFILE_SLIDER_LABEL"> 
			<field 
				name="organization" 
				type="text" 
				id="organization" 
				label="PLG_USER_TESTPROFILE_FIELD_ORGANIZATION_LABEL" 
				required="true" 
				class="validate-numeric" /> 
		</fieldset> 
	</fields> 
</form>

In this way the organization field is required and must be a number: with no sense in this case, but it is an easy test!

To create a custom validation code, simply replace the field class with a custom validation name, such as validate-minlenght2. After this put in the profiles folder a file called profile.js with the following content:

window.addEvent('domready', function() {
    document.formvalidator.setHandler('minlenght2',
        function (value) {
            if (value.length < 2) {
                return false;
            } else {
                return true;
            }
    });
});

This file defines an handler for the minlenght2 rule that checks the min length of the field value.

The last thing to do is to add this Javascript to our page. This can be done by adding the following instructions in a new method called onContentPrepare:

function onContentPrepare($article, $params, $limitstart) 
{ 
	$document = & JFactory::getDocument(); 
	$document->addScript(JURI::base(). "plugins/user/testprofile/profiles/profile.js");	 
}

Attention: you must use this method instead of onContentPrepareForm, otherwise your file will be loaded before the Mootools library, generating an error.

Server side validation

Server side validation requires the definition of a new rule. For the reasons expressed in the MVC tutorial, it's better to not create a generic rule (i.e. a length2 rule), but we must create a rule specific for every field.

To create an Organization rule we must create the corresponding rule class, so let's add the file organization.php in a newly created folder /profiles/rules with the following content.

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla formrule library
jimport('joomla.form.formrule');
class JFormRuleOrganization extends JFormRule
{
    protected $regex = '^.{2,}$';
}

To add this rule to our code, we need to modify the XML declaration of our plugin by adding the addrulepath attribute. If this attribute is added to the form tag is not recognised, so we add it to the fieldset tag.

To validate the organization field we can simply add the validation attribute to it. This is the complete code for the profile.xml file:

<?xml version="1.0" encoding="utf-8"?> 
<form> 
	<fields name="testprofile"> 
		<fieldset name="testprofile" 
			label="PLG_USER_TESTPROFILE_SLIDER_LABEL" 
			addrulepath="/plugins/user/testprofile/profiles/rules"> 
			<field 
				name="organization" 
				type="text" 
				id="organization" 
				label="PLG_USER_TESTPROFILE_FIELD_ORGANIZATION_LABEL" 
				required="true" 
				class="validate-minlenght2" 
				validate="organization" /> 
		</fieldset> 
	</fields> 
</form>

A complex server side validation

Server side validation done using a custom JformRule class can't access the value of other fields filled in the registration form, such as the username.

If you need this type of server side validation you have to put the validation code in a special method of the validation plugin: onUserBeforeSave.

As you can read in the documentation, this is an event triggered before user registration data are stored in the database.

The documentation affirms that this method doesn't return any value, but if you check the Joomla! code for the user registration in /libraries/joomla/user/user.php, you can see that, if this method returns false, the user is not saved into the database.

Let's modify our plugin by adding this method:

function onUserBeforeSave($data, $isNew, $newdata)
{
	$result = true;
	if ($newdata['testprofile']['organization'] == $newdata['username'])
	{
		$result = false;
	JError::raiseWarning(1000, 'Organization can\'t be equals to the username');
	}
	return $result;
}

This is a simple code that check that the organization field is different from the username. If they're equals an error is raised ad the user is not saved.

You can find here the Testprofile plugin completed with the validation explained. Have a good hack.

Comments   

 
#1 Nadeera 2013-09-15 09:32
Hi,
I have added custom text field called "NIC" and I need it to be unique value. (If there is same value exists for another user need to give error message when saving user data). Could you please explain me how to create validation rule for this?
Quote
 
 
#2 Edy Incoletti 2013-09-17 16:28
Quoting Nadeera:
Hi,
I have added custom text field called "NIC" and I need it to be unique value. (If there is same value exists for another user need to give error message when saving user data). Could you please explain me how to create validation rule for this?

Hi,
Your rule checks only a field, but the check differs when adding or modifying the record, because you have to exclude current record from your query.
Add the validation code to the onUserBeforeSav e function.
You can fine here some explanation on how to perform query in your function:
http://docs.joomla.org/Selecting_data_using_JDatabase
Quote
 
 
#3 Nadeera 2013-09-21 17:37
Quoting Edy Incoletti:
Quoting Nadeera:
Hi,
I have added custom text field called "NIC" and I need it to be unique value. (If there is same value exists for another user need to give error message when saving user data). Could you please explain me how to create validation rule for this?

Hi,
Your rule checks only a field, but the check differs when adding or modifying the record, because you have to exclude current record from your query.
Add the validation code to the onUserBeforeSave function.
You can fine here some explanation on how to perform query in your function:
http://docs.joomla.org/Selecting_data_using_JDatabase

Thanks for the nice reference. I'll look into it.
Quote
 
 
#4 Yiannis 2014-05-24 22:44
function onContentPrepar e is not triggered. Any ideas ? Thanks in advance. Great tutorial
Quote
 
 
#5 rafpelegri 2015-04-20 20:43
Use JText for error messages with language files:
JError::raiseWa rning(1000, JText::_('PLG_M SG_ERROR_IN_INI FILE'));
Quote