2012-01-13 107 views

回答

2

如果您正在捕获验证异常由用户模型引发,那么您的消息文件位置可能不正确。它需要是:'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' 
    ) 
); 

而且,违背迈克尔普的回应,你应该模型中的所有验证逻辑。控制器代码,注册一个新用户,应尽可能简单:

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'); 
} 
+0

谢谢你,解决了我的问题,但由于某些原因'_external”'不工作,它给我'注册/用户。 username.unique' insted的正常消息,我想要 – Linas 2012-01-14 14:12:48

+0

我认为外部消息需要在不同的文件中:./application/messages/registration/_external.php – badsyntax 2012-01-14 14:26:06

+0

我发现它是有用的检查消息文件核心验证类中的errors()方法的路径。 – badsyntax 2012-01-14 14:30:35

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保持大致相同,与固定了 'lenght' 拼写错误你有例外:

// ./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. 
)