The Form tutorial - normal Validation
- Posted by dlib on March 21st, 2008 filed in Form tutorial, Tutorials
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.
March 22nd, 2008 at 12:56 pm
Is it mandatory to use valid::email instead of email?
March 22nd, 2008 at 2:04 pm
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.
April 16th, 2008 at 9:29 pm
dlib_ thank you for all your tutorials! Very helpfull indeed
June 30th, 2008 at 1:56 am
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
June 30th, 2008 at 11:18 am
You downloaded the new Validation library from your svn. Your directory doesn’t indicate so
October 9th, 2008 at 7:10 pm
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
October 15th, 2008 at 1:26 pm
[...] Normal validation [...]