0

我有完全工作的验证脚本我的问题是我无法获得自定义错误消息

这是我的注册功能:http: //pastebin.com/ZF3UVxUr

这是我的消息数组: http: //pastebin.com/d9GUvM3N

我的消息脚本在:有\application\messages\registration.php什么建议吗?

对不起,长代码只是跳过 html 和其他东西

4

2 回答 2

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');
}
于 2012-01-14T11:55:37.820 回答
1

您应该在尝试访问任何模型之前验证发布数据。您的验证规则没有被执行,因为您没有执行验证 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'
    )
);

然后,发送一个空的“名称”字段将返回:

Array
(
    [name] => Please enter your username.
)
于 2012-01-13T22:43:21.553 回答