The Form tutorial - normal Validation

This post will concern itself with validating forms using the new validation library in Kohana. I’ve kept this simple as writing forms yourself including messages and populating is a pain in the ass. You can do the error messages yourself using the message() method and the errors() method.

Populating is done by taking the $_POST global and filling your inputs in the view with it.

class Test_Controller extends Controller {
 
	public function index()
	{
 
		$_POST=new Validation($_POST); //turn $_POST into array object
                //add rules, filters
		$_POST->pre_filter('ucfirst','name')
		      ->add_rules('name','length[0,50]')
		      ->add_rules('email','valid::email','required')
		      ->pre_filter('trim','comment');
 
 
		if($_POST->validate())
		{
			//Serialize the preference array
			$_POST['preference']=serialize($_POST['preference']);
 
			//Load model and set values
			$preference=new Preference_Model;
			$preference->name=$_POST['name'];
			$preference->email=$_POST['email'];
			$preference->preference=$_POST['preference'];
			$preference->comment=$_POST['comment'];
 
			//Save form into table
			if($preference->save())
			{
				echo 'We\'ve saved it.';
			}
			else
			{
				echo 'no saving today';
			}
		}
		else
		{
			$view=new View('tutorial_form');
			echo $view->render();
 
		         if($_POST->errors()!=array())
                         {
                              echo Kohana::debug($_POST->errors()); //outputs errors if any, you can handle them here with your own error messages
                         } 
		}
	}
}

The view is available on google code. I’ve kept it basic but you can use all the formatting you want.


7 Responses to “The Form tutorial - normal Validation”

  1. spirit Says:

    Is it mandatory to use valid::email instead of email?

  2. admin Says:

    I’m not sure, I haven’t looked at the source of the library for a while but I think a patch was added so you can leave out valid:: when you use a valid helper.

  3. JamesPaxi Says:

    dlib_ thank you for all your tutorials! Very helpfull indeed :)

  4. Chris Says:

    Fatal error: Call to undefined method Validation::pre_filters() in C:\wamp4\www\Kohana_v2.1.2\application\controllers\preference.php on line 8. I followed the tutorial and I cant seem to figure out this error.
    Thanks

  5. dlib Says:

    You downloaded the new Validation library from your svn. Your directory doesn’t indicate so

  6. h Says:

    I’m using kohana v. 2.2 and I am getting this error as I work with this tutorial. I also tried replacing Validation.php with the lastest version but I still have the same challenge:

    Fatal error: Call to undefined method Validation::pre_filter() in /kohana/application/controllers/test.php on line 8

    any ideas?

    -thanks

  7. Learning Kohana » The Form tutorial - the beginning Says:

    [...] Normal validation [...]

Leave a Comment