Walidacja formularzy

Z Joomla!WikiPL

Ikona przetlumacz.png
 Uwaga o zawartości

Ta strona wymaga przetłumaczenia lub jest w trakcie tłumaczenia! Pomoc jest mile widziana. Ostatnio edytowane przez Zwiastun (dyskusja. Data edycji: Tue, 10 Dec 2013 15:37:01 +0000


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

Włączenie walidacji

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


  • form-validate -> enable validation

Elementy formularza

  • 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 this to e.g. red background and white foreground, your users will be able to see which fields are wrong.

Really only accept 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='<?=JUtility::getToken()?>';//send token
		return true; 
	else {
		alert('Some values are not acceptable.  Please retry.');
	return false;
<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" />
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 if by a javascript error or other possibilities 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 succesfull.  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
	return false;

Własna obsługa

If you want a custome handler, you can add one to the class, as follow example (defined AFTER the validate.js):
Window.onDomReady(function() {
	document.formvalidator.setHandler('birth', function(value) {
		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!)

Dziękujemy za wkład

» Stefan Wajda [zwiastun],