加入用户模型
App::uses('SimplePasswordHasher','Controller/Component/Auth');
class User extends AppModel {
public $useTable = 'users';
public $hasMany = array(
'Reminder' => array(
'className' => 'Reminder'
)
);
public $validate = array(
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
),
'between' => array(
'rule' => array('between',5,15),
'message' => 'Between 5 to 15 characters'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Username is already taken'
)
),
'password' => array(
'between' => array(
'rule' => array('between',5,10),
'message' => 'Between 5 to 10',
),
'compareFields' => array(
'rule' => array('compareFields','confirm_password'),
'message' => 'Passwords do not match',
'required' => 'update'
)
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please enter valid email address'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'Email is already in use'
),
'compareFields' => array(
'rule' => array('compareFields','confirm_email'),
'message' => 'Emails do not match',
'required' => 'update'
)
),
'timezone' => array(
'isValid' => array(
'rule' => 'isValid',
'message' => 'Please select a timezone'
)
)
);
在用户控制器内部。
// Changed existing emails
if(!empty($this->request->data['User']['email'])) {
echo "Email is set <br/>";
$this->User->set($this->request->data['User']['email']);
if($this->User->validates(array('fieldList' => array('email')))) {
echo "Email is valid <br/>";
$this->User->id = $this->Session->read('Auth.User.id');
$this->User->saveField('email',$this->request->data['User']['email'],true);
$this->Session->setFlash("Settings updated");
}
}
// Change existing password
if(!empty($this->request->data['User']['password'])) {
echo "Password is set <br/>";
$this->User->set($this->request->data['User']['password']);
if($this->User->validates(array('fieldList' => array('password')))) {
echo "Password is valid <br/>";
$this->User->id = $this->Session->read('Auth.User.id');
$this->User->saveField('password', $this->request->data['User']['password'],true);
$this->Session->setFlash("Password changed");
}
}
我知道'saveField()'不会自动进行验证,因此我将验证参数设置为true,但无济于事。
我已经包含了包含验证的模型。
任何帮助都将不胜感激。
答案 0 :(得分:3)
<强>被修改强>:
我确实认为你必须像这样进行验证:
$this->User->id = $this->Session->read('Auth.User.id');
if(!$this->User->saveField('password', 'asdf', true)) {
echo "Invalid.";
pr($this->User->invalidFields());
} else {
echo "Saved!";
}
或者可选地执行此操作:
只需read()
数据,覆盖该数组中的新密码,然后$this->User->set()
并使用$this->User->validates()
。
请参阅here。