Kohana Validation Messages
October 27, 2012
In Kohana, you are able to add validation rules to a model. This is truly awesome, BUT displaying the validation error is not so automatic out of the box.
In your model you can set up rules like:
public function rules()
{
return array(
'username' => array(
array('not_empty')
),
);
}
If this is all you have and username is submitted as empty, kohana will throw an ugly exception “Failed to validate array”. What we need to do is set up a message to show if this situation ever happens. If your model is “user” create the file “user.php” in /application/messages. In that file set the messages:
return array
(
'username' => 'You submitted an empty username. Please fill it in.'
);
Then, before you are about to save username to a user model:
$user->username = $username_submitted;
if(!$user->validation->check())
{
//DISPLAY ERROR HERE
foreach($user->validation()->errors('user') as $error)
{
echo $error;
}
}
else
{
$user->save();
}
Hopefully Kohana will include better, prettier, and automatic validation layers in future releases but in the current, it’s not too bad.