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

validation function seems to be totally ignored on save()

Having a super-difficult time getting basic validation to happen on a model. Here's my very basic controller action for "providers/add":

public function addAction()
    {
        if ($this->request->isPost()) {
            $provider = new Providers();
            if ($provider->save($this->request->getPost())) {
                return $this->response->redirect('');
            } else {
                $this->flashSession->error(implode(', ', $provider->getMessages()));
                return $this->response->redirect('providers/add');
            }
        }
    }

And here is my model's validation function:

public function validation()
    {
        $this->validate(new PresenceOf(['field' => 'last_name']));
        $this->validate(new Email(['field' => 'email', 'allowEmpty' => true]));
        return $this->validationHasFailed() != true;
    }

The validation function seems to be totally ignored, because I never get an error message even when last_name is an empty string. I have even tried echoing some info in the validation function followed by "exit" but nothing happens, so it seems the validation function is never even run. Any ideas?



85.5k

sorry but jsut to be sure, the request is post right ? $this->request->isPost()

which phalcon version, 2.0 or 2.1 cuz thye changed the validations in 2.1

It's 2.0 -- after digging into the source code on github, I see this was happening b/c the validation goes thru a bunch of events and will exit the chain early on a validation error. In my case, it was the auto-checking for "notnull" columns based on the database introspection. I don't think this should happen, since the validator should continue to pick up ALL validation errors and not exit early. But at least I figured it out, and hopefully this behavior is fixed in 2.1.

I don't think this behaviour will be fixed any time soon - it's been the default behaviour for as long as I can remember.

Fortunately, there is a way to turn off the default NULL validation. Check the accepted answer here: https://forum.phalcon.io/discussion/3486/check-if-variable-is-empty-using-presenceof