我使用的是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);
}[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',
)
)
);我是不是遗漏了什么?
发布于 2013-04-09 05:01:20
对于这个解决方案,更好的方法可能是充分利用"required“和"allowEmpty”验证选项:
CakePhp's data validation
这就解决了我的问题,我认为这与我请求操作的方式有关,但实际上我甚至没有设置我想要验证的字段。
发布于 2012-11-05 13:55:48
我想通了。基本上我了解到,如果你不通过字段,那么它们将不会被验证。
https://stackoverflow.com/questions/12427164
复制相似问题