Jack George Wed Feb 29 17:33:17 -0500 2012

Subject: multiple validation rules for creation with single field update


I’ve got a question about validation with php activerecord, maybe somebody has an idea. I created a user model and added some validation rules. Now, when I create a new user, it works well that it validates e.g. the username, email and password (presence of, format etc.) but what if later I just want to update the email with a simple form (input: new email). I get validation errors that username and password are missing. I don’t want to use save(false) since some of the rules might make sense like the format of email rule. Is there a way to let it just validate some not all of the attributes? 'on' => 'create' is not helping, right? Since I do want the validation to take place on creation but then on saving a single attribute as well.

In my user model I have among others:

static $validates_presence_of = array(
array('username', 'message' => 'Please choose a username.'),
array('email', 'message' => 'Please enter your email address.'),
array('password', 'message' => 'Please choose a password.'),
static $validates_format_of = array(
'with' => '/^[a-z0-9\._-]+@([a-z0-9][a-z0-9-]*[a-z0-9]\.)+([a-z]+\.)?([a-z]+)$/',
'message' => 'Please enter a valid email address.'),
'with' => '/^[a-z]+[\w]*$/i',
'message' => 'Username must be alpha numeric.'),

In my controller for the new email I have among others:

$user = User::find($this->session->userdata('user_id'));
if ($user) {
$user->email = $_POST['email'];
if ($user->is_invalid()) die($user->errors);

Would greatly appreciate a hint! Maybe I'm misunderstanding validation with php activerecord. Thanks!