我遇到了一个奇怪的问题,在编辑视图中验证了用户名(如标题所示),这使我无法保存表单。我在这个视图中没有输入用户名,所以为什么这会被验证(并且失败)?
验证如下:
var $validate = array(
'username' => array(
'empty' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Username is required',
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This username has already been taken'
),
'pattern' => array(
'rule' => array('custom','/[a-zA-Z0-9\_\-]{6,}$/i'),
'message' => 'Must be 6 characters or longer with no spaces',
),
'length' => array(
'rule' => array('maxLength', 15),
'message' => 'Please keep username under 15 characters',
),
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Username cannot be empty',
)
);
下面的编辑功能:
function edit($id = null) {
$this->set('title_for_layout', 'Edit Profile');
unset($this->User->validate['email']['email']);
unset($this->User->validate['username']);
if($this->Auth->user('id')==$id) {
$this->set('user', $this->User->read(null, $id));
} else {
$this->Session->setFlash(__('You are not authorised to edit other member profiles', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('Your profile has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Your profile could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->User->read(null, $id);
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}
我取消设置username
然后只允许我保存表单,但这不是正确的方法。任何人都可以对此有所了解吗?
非常感谢!
答案 0 :(得分:1)
required => true
使'用户名'键成为必填字段,这意味着如果您只是尝试更新设置或没有用户名密钥的内容,则会失效。
我自己没有这样做,但尝试将'on' => 'create'
添加到empty
规则中,以便它仅在创建记录时适用。