2012-09-14 58 views
0

我正在使用CakePHP 2.1.1,而我的方法使用窗體幫助器,例如我的用戶控制器中的add方法驗證正確,我無法在控制器中驗證我的mobile_register方法來驗證,即使在數據丟失。CakePHP JSON後驗證不起作用?

這是我mobile_register方法:

public function mobile_register() { 

    if ($this->request->is('post')) { 
     $jsonData = file_get_contents("php://input"); 

     if(isset($jsonData) && !empty($jsonData)){ 
      $data = json_decode($jsonData,true);  
      $data = $this->User->configureUser($data); 
      $this->User->create(); 

      if($this->User->save($data)){ 
       $jsonResponse = array('status' => 'OK', 'token' => $data['User']['token'], 'message' =>'SUCCESS'); 
      }else{ 
       $errors = $this->User->validationErrors; 
       $this->log($errors,'errors'); 
       $jsonResponse = array('status' => 'ERROR','message' => $errors); 
      } 
     } 
    }else{ 

     $jsonResponse = array('status' => 'ERROR','message' => 'API method expects POST data'); 
    } 

    $this->set('response' , $jsonResponse); 

} 

我一直在使用curl來測試我的方法,它總是儘管發佈了以下數據保存:

[User] => Array 
    (
     [firstname] => Andy 
     [token] => cc42030bbb49faf2cf0393418036e44f 
     [role] => user 
    ) 

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"User":{"firstname":"Andy"}}' url/users/mobile_register 

我的驗證規則,在我的模型是:

public $validate = array(
    'username' => array(
     'username-1' => array(
      'rule' => array('notempty'), 
      'message' => 'Username is required', 
     ), 
     'username-2' => array(
      'rule' => 'alphaNumeric', 
      'message' => 'Usernames must only contain letters and numbers.', 
     ), 
    ), 
    'password' => array(
     'password-1' => array(
      'rule' => array('notempty'), 
      'message' => 'Password is required', 
     ), 
     'password-2' => array(
      'rule' => array('between', 5, 15), 
      'message' => 'Passwords must be between 5 and 15 characters long.', 
     ), 

    ), 
    'firstname' => array(
     'notempty' => array(
      'rule' => array('notempty'), 
      'message' => 'Forename is required' 
     ), 
    ), 
    'surname' => array(
     'notempty' => array(
      'rule' => array('notempty'), 
      'message' => 'Surname is required', 
     ), 
    ), 
    'email' => array(
     'email-1' => array(
      'rule' => 'notempty', 
      'message' => 'Email is required', 
     ), 
     'email-1' => array(
      'rule' => 'email', 
      'message' => 'Please enter a valid email', 
     ) 
    ) 

); 

我錯過了什麼嗎?

回答

0

我想通了。基本上我瞭解到,如果你不通過這些字段,那麼他們將不會被驗證。

0

也許該解決方案更好的辦法是很好地利用的「必需」和「allowEmpty」驗證選項:

CakePhp's data validation

這是解決我的問題,我認爲這是與我要求採取行動的方式有關,但相反,我甚至沒有設置我想驗證的字段。