Actions

Difference between revisions of "Client-side form validation"

From Joomla! Documentation

(Added CSS example. Corrected some typographical errrors.)
Line 1: Line 1:
 
[[Category:Development]]
 
[[Category:Development]]
 
+
==Introduction==
== Intro ==
+
 
+
 
Joomla 1.5 contains a behavior '''JHTMLBehavior::formvalidation()''' which enables the script '''validate.js'''.
 
Joomla 1.5 contains a behavior '''JHTMLBehavior::formvalidation()''' which enables the script '''validate.js'''.
 
It uses '''mootools''' and allows your form and its elements to be validated.   
 
It uses '''mootools''' and allows your form and its elements to be validated.   
Line 8: Line 6:
 
'''Note:''' For more recent versions of Joomla (1.5.2) use '''JHTML::_('behavior.formvalidation')''' instead of '''JHTMLBehavior::formvalidation()'''
 
'''Note:''' For more recent versions of Joomla (1.5.2) use '''JHTML::_('behavior.formvalidation')''' instead of '''JHTMLBehavior::formvalidation()'''
  
== To enable the validation ==
+
==Enable the Validation==
The only thing you have to do is set the '''classes''' of the form and elements to specified meanings.
+
The only thing you have to do is set the '''classes''' of the form and elements to the specified meanings.
 
Classes:
 
Classes:
=== Form ===
+
===Form===
 
* form-validate -> enable validation
 
* form-validate -> enable validation
=== Form elements ===
+
===Form elements===
 
* required
 
* required
 
* validate-username
 
* validate-username
Line 20: Line 18:
 
* validate-email
 
* validate-email
 
* validate-[custom] -> custom handlers have to be set then!
 
* validate-[custom] -> custom handlers have to be set then!
== Style invalid elements ==
+
==Style Invalid Elements==
 
If some elements don't validate they will get the class
 
If some elements don't validate they will get the class
 
* invalid
 
* invalid
If you style this to e.g. red background and white foreground, your users will be able to see which fields are wrong.
+
If you style the class in the cascading style sheet, your users will be able to see which fields are wrong. For instance:
 
+
<source lang="css">
== Really only accept form after validation ==
+
.invalid {color:red;}
If you don't want the form to submit anything unless the values are validated, here's a nice script:<source lang="php">
+
</source>
 +
==Only Accept the Form After Validation==
 +
If you don't want the form to submit anything unless the values are validated, here's a nice script:
 +
<source lang="php">
 
<?php JHTMLBehavior::formvalidation(); ?>
 
<?php JHTMLBehavior::formvalidation(); ?>
 
<script language="javascript">
 
<script language="javascript">
 
function myValidate(f) {
 
function myValidate(f) {
if (document.formvalidator.isValid(f)) {
+
  if (document.formvalidator.isValid(f)) {
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
+
      f.check.value='<?php echo JUtility::getToken(); ?>'; //send token
return true;  
+
      return true;  
}
+
  }
else {
+
  else {
alert('Some values are not acceptable.  Please retry.');
+
      alert('Some values are not acceptable.  Please retry.');
}
+
  }
return false;
+
  return false;
 
}
 
}
 
</script>
 
</script>
Line 48: Line 49:
 
</form></source>
 
</form></source>
  
The page that receives the value can check several things:<source lang="php">
+
The page that receives the value can check several things:
 +
<source lang="php">
 +
 
 
defined( '_JEXEC' ) or die( 'Restricted access' );  //Verify Joomla enabled
 
defined( '_JEXEC' ) or die( 'Restricted access' );  //Verify Joomla enabled
 
 
$jAp=& JFactory::getApplication();
 
$jAp=& JFactory::getApplication();
 
if ($_POST['check']!=JUtility::getToken()) {
 
if ($_POST['check']!=JUtility::getToken()) {
//First verify if by a javascript error or other possibilities the form has not been submitted without the validation
+
  // First verify (by a Javascript error or other methods) that the form has not been submitted without the validation
if ($_POST['check']=='post') $jAp->enqueueMessage('Please check all the fields of the form, aub.<br/>
+
  if ($_POST['check']=='post') $jAp->enqueueMessage('Please check all the fields of the form, aub.<br/>
If your browser blocks javascript, then this form will never be succesfull. This is a security measure.','error');
+
If your browser blocks Javascript, then this form will never be successful. This is a security measure.','error');
//If then still the check isn't a valid token, do nothing as this might be a spoof attack or other invalid form submission
+
  // If the check still isn't a valid token, do nothing. This might be a spoof attack or other invalid form submission
return false;
+
  return false;
}</source>
+
}
 
+
</source>
== Custom handlers ==
+
==Custom Handlers==
If you want a custome handler, you can add one to the class, as follow example (defined AFTER the validate.js):<source lang="php">Window.onDomReady(function() {
+
If you want a custom handler, you can add one to the class, as in the following example (defined AFTER the validate.js):
document.formvalidator.setHandler('birth', function(value) {
+
<source lang="php">Window.onDomReady(function() {
regex=/^\d{4}(-\d{2}){2}$/;
+
  document.formvalidator.setHandler('birth', function(value) {
return regex.test(value);
+
      regex=/^\d{4}(-\d{2}){2}$/;
})
+
      return regex.test(value);
})</source>
+
  })
 +
})
 +
</source>
 
You can then set any class to validate-birth to make it validate as yyyy-mm-dd.  (Valid date is not checked!)
 
You can then set any class to validate-birth to make it validate as yyyy-mm-dd.  (Valid date is not checked!)

Revision as of 18:04, 17 January 2010

Contents

Introduction

Joomla 1.5 contains a behavior JHTMLBehavior::formvalidation() which enables the script validate.js. It uses mootools and allows your form and its elements to be validated.

Note: For more recent versions of Joomla (1.5.2) use JHTML::_('behavior.formvalidation') instead of JHTMLBehavior::formvalidation()

Enable the Validation

The only thing you have to do is set the classes of the form and elements to the specified meanings. Classes:

Form

  • form-validate -> enable validation

Form elements

  • required
  • validate-username
  • validate-password
  • validate-numeric
  • validate-email
  • validate-[custom] -> custom handlers have to be set then!

Style Invalid Elements

If some elements don't validate they will get the class

  • invalid

If you style the class in the cascading style sheet, your users will be able to see which fields are wrong. For instance:

.invalid {color:red;}

Only Accept the Form After Validation

If you don't want the form to submit anything unless the values are validated, here's a nice script:

<?php JHTMLBehavior::formvalidation(); ?>
<script language="javascript">
function myValidate(f) {
   if (document.formvalidator.isValid(f)) {
      f.check.value='<?php echo JUtility::getToken(); ?>'; //send token
      return true; 
   }
   else {
      alert('Some values are not acceptable.  Please retry.');
   }
   return false;
}
</script>
<form id="WV-form" method="post" class="form-validate" onSubmit="return myValidate(this);">
<input type="hidden" name="check" value="post"/>
...
<input type="text" name="email" size="30"  class="required validate-email"/>
...
<input type="submit" value="Submit" />
</form>

The page that receives the value can check several things:

defined( '_JEXEC' ) or die( 'Restricted access' );  //Verify Joomla enabled
$jAp=& JFactory::getApplication();
if ($_POST['check']!=JUtility::getToken()) {
   // First verify (by a Javascript error or other methods) that the form has not been submitted without the validation
   if ($_POST['check']=='post') $jAp->enqueueMessage('Please check all the fields of the form, aub.<br/>
If your browser blocks Javascript, then this form will never be successful. This is a security measure.','error');
   // If the check still isn't a valid token, do nothing. This might be a spoof attack or other invalid form submission
   return false;
}

Custom Handlers

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

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

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