我有完全正常工作的验证脚本我的问题是我无法获得自定义错误消息
以下是我的注册功能:http://pastebin.com/ZF3UVxUr
这是我的消息数组:http://pastebin.com/d9GUvM3N
我的消息脚本位于:\application\messages\registration.php
有任何建议吗?
很抱歉长代码只是跳过html和其他东西
答案 0 :(得分:2)
如果您正在捕获User模型引发的验证异常,那么您的消息文件位置可能不正确。它必须是:'registration / user.php'。
// ./application/messages/registration/user.php
return array(
'name' => array(
'not_empty' => 'Please enter your username.',
),
'password' => array(
'matches' => 'Passwords doesn\'t match',
'not_empty' => 'Please enter your password'
),
'email' => array(
'email' => 'Your email isn\'t valid',
'not_empty' => 'Please enter your email'
),
'about-me' => array(
'max_length' => 'You cann\'ot exceed 300 characters limit'
),
'_external' => array(
'username' => 'This username already exist'
)
);
此外,与Michael P的回复相反,您应该将所有验证逻辑存储在模型中。注册新用户的控制器代码应该如下所示:
try
{
$user->register($this->request->post());
Auth::instance()->login($this->request->post('username'), $this->request->post('password'));
}
catch(ORM_Validation_Exception $e)
{
$errors = $e->errors('registration');
}
答案 1 :(得分:1)
在尝试点击任何模型之前,您应该验证帖子数据。您的验证规则未执行,因为您尚未执行validation check()。
我会做类似的事情:
// ./application/classes/controller/user
class Controller_User extends Controller
{
public function action_register()
{
if (isset($_POST) AND Valid::not_empty($_POST)) {
$post = Validation::factory($_POST)
->rule('name', 'not_empty');
if ($post->check()) {
try {
echo 'Success';
/**
* Post is successfully validated, do ORM
* stuff here
*/
} catch (ORM_Validation_Exception $e) {
/**
* Do ORM validation exception stuff here
*/
}
} else {
/**
* $post->check() failed, show the errors
*/
$errors = $post->errors('registration');
print '<pre>';
print_r($errors);
print '</pre>';
}
}
}
}
Registration.php大致保持不变,除了修复你所遇到的“长度”拼写错误:
// ./application/messages/registration.php
return array(
'name' => array(
'not_empty' => 'Please enter your username.',
),
'password' => array(
'matches' => 'Passwords doesn\'t match',
'not_empty' => 'Please enter your password'
),
'email' => array(
'email' => 'Your email isn\'t valid',
'not_empty' => 'Please enter your email'
),
'about-me' => array(
'max_length' => 'You cann\'ot exceed 300 characters limit'
),
'_external' => array(
'username' => 'This username already exist'
)
);
然后,发送一个空的'name'字段将返回:
Array
(
[name] => Please enter your username.
)