2012-01-13 110 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. 
)