【发布时间】:2012-03-24 10:05:57
【问题描述】:
我正在为我的模型中的验证规则使用自定义方法(使用 Kohana 3.2)。我遵循the documentation 中列出的格式。
// Calls A_Class::a_method($value);
array(array('A_Class', 'a_method')),
但如果规则失败,我似乎无法弄清楚如何添加自定义错误消息。
有什么帮助吗?
【问题讨论】:
我正在为我的模型中的验证规则使用自定义方法(使用 Kohana 3.2)。我遵循the documentation 中列出的格式。
// Calls A_Class::a_method($value);
array(array('A_Class', 'a_method')),
但如果规则失败,我似乎无法弄清楚如何添加自定义错误消息。
有什么帮助吗?
【问题讨论】:
对于这个例子,我们将假设一个模态“用户”并验证字段“用户名”
/application/classes/model/user.php
class Model_User extends ORM
{
public function rules()
{
return array(
'username' => array(
array('not_empty'),
array('A_Class::a_method', array(':value')),
)
);
}
}
A_Class
public static function a_method($value)
{
// Validate and return TRUE or FALSE
}
/application/messages/forms/user.php
添加了一个表单文件夹,以便显示我们可以选择消息文件以加载错误。消息文件匹配模型名称(用户)
return array(
'username' => array(
'not_empty' => 'Custom error message for not_empty method',
'A_Class::a_method' => 'Custom error message for you own validation rule...'
),
);
现在在您的控制器中验证并显示错误消息
class Controller_User extends Controller
{
// User model instance
$model = ORM::factory('user');
// Set some data to the model
$model->username - 'bob';
// Try to validate and save
try
{
$model->save()
}
catch (ORM_Validation_Exception $e)
{
// Loads messages from forms/user.php
$errors = $e->errors('forms');
// See the custom error messages
echo Debug::vars($errors);
)
)
【讨论】: