Nicholas Morgan Mon Nov 14 22:54:51 -0500 2011

Subject: Stupid question - should all validations be done in a model?

Here is a somewhat simple question that I have been wondering for a while now.

Should all validations be done in a Model? Are there any situations where it is better to do validations in a controller?

I am facing the following problems due to validations being done in a model:

1) Errors (if any) are returned into a giant array. This is okay, but it does not allow me to place a custom error for each field. For example, I can't figure out a way to place individual errors next to every invalid field in a HTML form. I can only place one giant error message at the top of the page for when a HTML form is invalid.

2) I am also facing fierce trouble validating a password. In my user registration form, I have fields for "password" and "password_confirmation", with no way inside my model to ensure that they are equal before hashing the password and saving it. The way I currently do this is with extra code inside my controller, but extra code inside my controller is icky and not preferred. I feel like there should be some kind of way in PHP ActiveRecord to validate that "password" and "password_confirmation" are equal before saving a record, and ONLY saving "password" (there is no need to save "password_confirmation" into a separate field).


Brandon M Thu Nov 17 10:13:32 -0500 2011

For #2:

In my model I set:

public $confirm;

Validation:

public function validate(){
    if($this->confirm != ''){
        if($this->password != $this->confirm){
            $this->errors->add('password','does not match.');
        }
    }
}

Then you can set password and confirm and when you $model->save() confirm is ignored.

Nicholas Morgan Sat Nov 19 17:40:59 -0500 2011

I don't understand at all why you have the if($this->confirm != '') part.

Nicholas Morgan Sun Nov 20 06:09:23 -0500 2011

delete

(1-3/3)