作者:小洲相册居士 | 来源:互联网 | 2014-03-27 00:19
Kohana表单验证Validation官方教程写的有点粗糙,我也是看了半天才明白。本教程是连载教程,数据还是上一讲的数据结构(KohanaORM)第一步:在application/model/a
Kohana 表单验证Validation官方教程写的有点粗糙,我也是看了半天才明白。本教程是连载教程,数据还是上一讲的数据结构(Kohana ORM)
第一步:在application/model/article.php中书写验证规则:
//验证规则
public function rules()
{
return array(
'cid' => array(
array('not_empty')
),
'title' => array(
array('not_empty'),
),
'content' => array(
array('not_empty'),
array('min_length', array(':value', 4)),
array('max_length', array(':value', 40)),
),
);
}
第二步:application/messages/models/article.php中编写验证提示信息(没有的目录请自行创建) */
return array(
'cid' => array(
'not_empty' => '文章分类不能为空'
),
'title' => array(
'not_empty' => '文章标题不能为空'
),
'content' => array(
'not_empty' => '文章内容不能为空',
'min_length' => '内容至少4个字符',
'max_length' => '内容不能超过40个字符'
)
);
第三步:编写前台html文件:application/views/welcome/index.php
" method="post">
分类:
= Arr::get($errors, 'cid'); ?>
标题:= Arr::get($errors, 'title'); ?>
内容:
= Arr::get($errors, 'content'); ?>
第四步:编写Controller文件application/controller/welcome.php:find_all();
$this->template->category = $category;
if($_POST)
{
$artile = ORM::factory('article')->values($_POST);
$vali = Validation::factory($_POST, '_external', array());
try{
$artile->save($vali);
}
catch (ORM_Validation_Exception $e)
{
$this->template->errors = $e->errors('models');
}
}
}
}
不符合验证规则,将提示错误,如下图: