jQuery validation library

jQuery is a great javascript library and comes with a great validation plugin. I wrote a Kohana library to make the validation plugin work together with Kohana’s Forge library. It’s easy to work with, just pass the Forge object to the library and it’ll create the proper validation code.

To make it work I extended the Forge library with two methods: get_attr() to fetch set attributes of the <form> element and error_message() to fetch the proper error message.

The files can be found here: Jquery_Validation.php and MY_Forge.php

Installation

Installing is easy, copy MY_Forge.php and Jquery_Validation.php into your application/libraries directory. MY_Forge extends the Forge library and Jquery_Validation does the actual magic.

Example

public function add_article()
{
	$form = new Forge();
	$form->set_attr('id','event')->set_attr('class','ala');
	$form->input('titel')->label(true)->rules('required|valid_email');
	$form->input('text')->label(true)->rules('required');
	$form->submit('Send')->set_label(true);	
 
	if ($form->validate())
	{ //some stuff 
 
	}
        $this->template=new View('template');
        $this->template->form=$form->render();
        $this->template->form_js=Jquery_Validation::factory($form);
 
}

The last line does the magic. Important you must set an id of the form with set_attr(), otherwise it won’t work.
The view file

< head>
< script type="text/javascript" src="http://localhost/chocolade/assets/js/jquery.js">
< script type="text/javascript" src="http://localhost/chocolade/assets/js/jquery.delegate.js">
< script type="text/javascript" src="http://localhost/chocolade/assets/js/jquery.validate.pack.js">
< script type="text/javascript"><?=$this->template->form_js ?></ script>
 
< body>
<?=$this->template->form ?></ script>

The second echo outputs the form, the first the validation in jQuery. $this->template->form_js will look like this:

$().ready(function() {$("#event").validate({"rules":{"titel":{"required":true,"email":true}
,"text":{"required":true}},"messages":{"titel":{"required":"Het veld is verplicht.",
"email":"Het  veld moet een geldig e-mailadres zijn."},
"text":{"required":"Het  veld is verplicht."}}});});

The form will look like a form. jQuery validation will work immediatly.

Other methods:

Jquery_Validation::as_array() //returns rules and errors as an array
Jquery_Validation::as_json()//returns rules and errors as a json-object 
//which can be fed to jQuery
Jquery_Validation::jquery_validation();//called by the __toString method
// outputs the entire validation code
Jquery_Validaiton::load(Forge $form) takes an Forge form object 
//as argument and does the magic of translating Kohana's rules to jQuery rules.

Leave a Comment