I have a user model. In it, I have set validations that are used while registering user. That works fine. But when user edits his profile information, I don't want to validate some fields like password, email, etc. How it is possible. Below is code.
<?php
class User extends AppModel{
var $name = 'User';
// used when user registers
var $validate = array(
'login' => array(
'minLength' => array(
'rule' => array('minLength', '6'),
'field' => 'login',
'message' => 'mimimum 6 characters long'
)
),
'password' => array( // don't want to validate in edit profile page
'minLength' => array(
'rule' => array('minLength', '6'),
'field' => 'password',开发者_Python百科
'message' => 'minimum 6 characters long'
)
),
'email' => array(
array(
'rule' => 'email',
'message' => 'please enter a valid email address'
)
)
);
?>
Above is used when I register a user. But when user edits his profile, I don't allow to edit/change user password. So each time while editing profile, it checks for password validation. I haven't added password field in edit profile page, I don't want to validate password field. So can I have different validation rules for different actions?
Thanks.
Several ways to do this:
- Use the
on
parameter to apply rules only to create or update actions. unset
the undesired rules from the model before validation.unset($this->User->validate['password']);
Use custom validation methods that are intelligent enough to figure out whether they should apply or not, e.g. by checking whether
$this->id
or$data['id']
is set or not. Not recommended unless you're sure what you're doing.Use the
$fieldlist
parameter of thesave
method to limit saving and validation to specified fields only. Fields not in the list will neither be saved nor validated. Very recommended, since it also protects against form spoofing.$this->User->save($this->data, true, array('only', 'certain', 'fields'));
just do until this:
var $validate = array(
'login' => array(
'minLength' => array(
'rule' => array('minLength', '6'),
'field' => 'login',
'message' => 'mimimum 6 characters long'
)
),
for a simple way to validate try jquery validation.
Try this:
<?php
class User extends AppModel{
var $name = 'User';
// used when user registers
var $validate = array(
'login' => array(
'minLength' => array(
'rule' => array('minLength', '6'),
'field' => 'login',
'message' => 'mimimum 6 characters long'
)
),
'password' => array( // don't want to validate in edit profile page
'minLength' => array(
'rule' => array('minLength', '6'),
'field' => 'password',
'message' => 'minimum 6 characters long',
'on' => 'create' //Only perform validation when creating a new record.
)
),
'email' => array(
array(
'rule' => 'email',
'message' => 'please enter a valid email address'
)
)
);
?>
Note the new line in the validation array for password.
This is documented in the Cookbook.
精彩评论