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

Give custom model validation priority

Hi,

I want to override the default messages that are shown to the user when a field is missing or malformed. So, I have built my own validation() method in my model. Unfortunately, when a required field is missing, that method never gets called because Phalcon runs its own validation, sees that the fields are missing, then stops.

Is there any way to make my custom validation() method run first, then have the built-in validation only run if my validation succeeds? Otherwise I don't see a way to change the messages being displayed to the user.

Just for reference, my custom validation method looks like this:

public function validation(){

        $this->validate(new \Phalcon\Mvc\Model\Validator\PresenceOf([
            'field'=>'first_name',
            'message' => 'First name is required'
        ]));

        return $this->validationHasFailed() != true;
}


26.3k
Accepted
answer

Hi!

My solution to this has two parts:

(1) Switch off the default notNullValidations validators

Do this in initialize() method


public function initialize() {

        //switching off the default notNullValidations validators
        $this->setup(
            array('notNullValidations'=>false)
        );

    }

Other way to do this is described here https://forum.phalcon.io/discussion/1497/validation-with-presenceof-not-working

(2) Flush former messages

Do this at the begining of the validation() method.

public function validation(){

        //flushing the array with error messages
        $this->_errorMessages = array();

        $this->validate(new \Phalcon\Mvc\Model\Validator\PresenceOf([
            'field'=>'first_name',
            'message' => 'First name is required'
        ]));

        return $this->validationHasFailed() != true;
}

This part is not necessary but I am doing it because of some other reasons, check this topic Hehe, it is our conversation by the way! ;) (needed to change account).

This works for me! ;)

Heh - what goes around comes around. Good tip - thanks.