我正在使用CakePHP 2.1.1,虽然我使用表单助手的方法,例如我的用户控制器中的add方法验证正确,我无法在控制器中获取我的mobile_register方法进行验证,它甚至可以节省当数据丢失时。
这是我的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)
这个解决方案的更好方法可能是充分利用“required”和“allowEmpty”验证选项:
这就解决了我的问题,我认为这与我请求操作的方式有关,而是我甚至没有设置我想要验证的字段。
答案 1 :(得分:-1)
我明白了。基本上我了解到,如果你没有通过这些字段,那么它们将无法通过验证。