Difference between revisions of "Client-side form validation"

From Joomla! Documentation

(Major update of the page)
m (JSplit template)
(2 intermediate revisions by one other user not shown)
Line 1: Line 1:
 +
{{JSplit}}
 
==Introduction==
 
==Introduction==
  
Line 23: Line 24:
 
Add a validation class to your form field declarations. Joomla adds a ''blur'' handler to validate the form field when the user moves away from the field.
 
Add a validation class to your form field declarations. Joomla adds a ''blur'' handler to validate the form field when the user moves away from the field.
 
<source lang="xml">
 
<source lang="xml">
<field name="email" type="text"
+
<field name="email" type="text" class="required validate-email" size="30" />
    class="required validate-email"
+
 
    size="30" />  
+
//For radios make sure the class is applied to the options:
 +
 +
<field name="ThisorThat" type="radio" label="Please say if it was full-time or the part-time equivalent?" >
 +
<option value="This" class="required">This</option>
 +
<option value="That" class="required">That</option>
 +
</field>
 
</source>
 
</source>
  
Line 68: Line 74:
 
</source>
 
</source>
  
==Style Invalid Elements==
+
==Styling/Templating Invalid Elements==
  
 
Joomla assigns the ''invalid'' class to form fields that do not pass the validation test. ''invalid'' is also added to the field labels.
 
Joomla assigns the ''invalid'' class to form fields that do not pass the validation test. ''invalid'' is also added to the field labels.
Line 85: Line 91:
  
  
==Work Around when Using with JToolBar==
+
==Problem & workaround with JToolBar==
 
If you are using JHTML::_('behavior.formvalidation') with JToolBar, for example use in backend, the above method will not work. This is because it depends on onSubmit event which did not fire when we call form.submit via JavaScript. To work around this, we have to move the code in onSubmit to be in submitbutton function override. This will look like this:-
 
If you are using JHTML::_('behavior.formvalidation') with JToolBar, for example use in backend, the above method will not work. This is because it depends on onSubmit event which did not fire when we call form.submit via JavaScript. To work around this, we have to move the code in onSubmit to be in submitbutton function override. This will look like this:-
 
<source lang="javascript">
 
<source lang="javascript">
Line 114: Line 120:
 
</script>
 
</script>
 
</source>
 
</source>
 +
 +
==More on mootools validation==
 +
More available classes on the mootools site here: [http://mootools.net/docs/more/Forms/Form.Validator#Validators http://mootools.net/docs/more/Forms/Form.Validator#Validators]
 +
 +
 +
==Server- or Client-side validation?==
 +
[[Form validation]]
 +
 
<noinclude>[[Category:Tutorials]][[Category:Development]][[Category:Component Development]]</noinclude>
 
<noinclude>[[Category:Tutorials]][[Category:Development]][[Category:Component Development]]</noinclude>

Revision as of 20:39, 27 May 2013

Split-icon.png
Split Page into Specific Joomla! Versions - J2.5 and 3.x

It has been suggested that this article or section be split into specific version Namespaces. (Discuss). If version split is not obvious, please allow split request to remain for 1 week pending discussions. Proposed since 10 years ago.

Introduction[edit]

Joomla 1.5 and later versions contain a behavior, which allows your form and its elements to be validated at client side, i.e., before it is submitted to the server. The behavior enables the script validate.js and uses MooTools.

Note: Validate.js is a validation system different from the one provided by MooTools.

Enable the Validation[edit]

Add a behavior to your form view template. For Joomla versions before 1.5.2:

JHTMLBehavior::formvalidation();

For versions from 1.5.2:

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

Add the form-validate class to your form

<form class="form-validate"> ... </form>

Add a validation class to your form field declarations. Joomla adds a blur handler to validate the form field when the user moves away from the field.

<field name="email" type="text" class="required validate-email" size="30" />

//For radios make sure the class is applied to the options: 
 
<field name="ThisorThat" type="radio" label="Please say if it was full-time or the part-time equivalent?" >
 <option value="This" class="required">This</option>
 <option value="That" class="required">That</option>
</field>

The following classes are available:

  • required
  • validate-username
  • validate-password
  • validate-numeric
  • validate-email
  • validate-[custom] -> custom defined - see below

Note: Joomla 2.5 translates the required field attribute into a required class value.

Finally, add the validate class to your submit button. This will cause an onclick handler to be added that validates the whole form. The form will only be submitted if it is valid.

<button type="submit" class="validate">Submit form</button>

Custom Handlers[edit]

If you want a custom handler, you can add one to the class, as in the following example (to be defined AFTER loading validate.js):

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

You can then assign validate-birth to any field to make it validate as yyyy-mm-dd. (Valid date is not checked!)

If you want a custom handler to check both the passwords (Password and Confirm Password) are same, please add the following script after the validate.js:

window.addEvent('domready', function(){
    document.formvalidator.setHandler('passverify', function (value) {
        return ($('password').value == value); 
    });
});

Add the class "validate-passverify" to the input field as below:

<input class="inputbox required validate-passverify" type="password" id="password2" name="password2" size="40" value="" />

Styling/Templating Invalid Elements[edit]

Joomla assigns the invalid class to form fields that do not pass the validation test. invalid is also added to the field labels. If you style the class in the cascading style sheet, your users will be able to see which fields are wrong. For instance:

.invalid {
    border-color: red !important;
}

Some site templates may already contain such definition. (This one is taken from beez_20.)



Problem & workaround with JToolBar[edit]

If you are using JHTML::_('behavior.formvalidation') with JToolBar, for example use in backend, the above method will not work. This is because it depends on onSubmit event which did not fire when we call form.submit via JavaScript. To work around this, we have to move the code in onSubmit to be in submitbutton function override. This will look like this:-

<script type="text/javascript">
/* Override joomla.javascript, as form-validation not work with ToolBar */
function submitbutton(pressbutton) {
    if (pressbutton == 'cancel') {
        submitform(pressbutton);
    }else{
        var f = document.adminForm;
        if (document.formvalidator.isValid(f)) {
            f.check.value='<?php echo JUtility::getToken(); ?>'; //send token
            submitform(pressbutton);    
        }
        else {
            var msg = new Array();
            msg.push('Invalid input, please verify again!');
            if ($('title').hasClass('invalid')) {
                msg.push('<?php echo JText::_('COM_JONGMAN_ERROR_SCHEDULE_TITLE_IS_REQUIRED')?>');    
            }
            if($('admin_email').hasClass('invalid')){
                msg.push('<?php echo JText::_('COM_JONGMAN_ERROR_INVALID_EMAIL')?>');
            }
            alert (msg.join('\n'));
        }
    }    
}
</script>

More on mootools validation[edit]

More available classes on the mootools site here: http://mootools.net/docs/more/Forms/Form.Validator#Validators


Server- or Client-side validation?[edit]

Form validation