We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Where is the best place to validate a model property?

I have a model and I want to validate some of its properties. I'm using getters and setters so I have these options:

I could validate the property directly in the setter method like so:

class Users extends Model
{
    protected $email;

    public function setEmail($email)
    {
        if(!$email = filter_var($email, FILTER_VALIDATE_EMAIL)){
            throw new \InvalidArgumentException('The email is not valid');
        }

        $this->email = $email;

        return $this;
    }
}

or I could validate it in the validation method:

class Users extends Model
{
    protected $email;

    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }

    public function validation()
    {
        $validator = new Validation();

        $validator->add('email', new \Phalcon\Validation\Validator\Email(
            [
                'message' => 'The e-mail is not valid'
            ]
        ))->add('email', new \Phalcon\Validation\Validator\PresenceOf(
            [
                'message' => 'The e-mail is required'
            ]
        ));

        return $this->validate();
    }
}

I understand that for some cases where a rule depends of mulitple fields, I have no choice but to validate in the validation() method, but as in the email example above I don't need to.

So I'm wondering if it's best to keep everything together in the validation() method, or try to keep the validation close to the property assignment.

The first example has the advantage that it won't allow the program to continue if the email is invalid, instead of going through all the assignments and then triggering the error.

The validation() method has the advantage of keeping all checks together, I guess?

What do you think?



51.1k

In the end, you can work as you like. But, my recommendation is to always use validation() . I had bad experience with people validation all over the code - a pain in the a...s It's good for you and for your co-workers (if there are any) to follow one simple logic. If you have to implement a complex validation, create your own validator and use it in validation() method .

Another good point is that when you validate inside validation() method you create an array of validation messages.

edited Oct '15

Im using validation() method, its tottaly fine. But i implemented my some own methods, espiecially MultiplePresenceOf and MultipleRegex to adding all fields one as array and in class foreach on all fields.