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

Phalcon validation

Hello, i'm just starting to learn Phalcon and i have run in to one problem with validation. How can i "echo" only one message from a certain data set of Validation or Form class instance?

Example 1 (for Form instance)

    ...
    $email = new Text('email');
    $email->addValidators(array(
        new PresenceOf(array(
                'message' => 'Message 1'
        )),
        new Email(array(
            'message' => 'Message 2'
        ))
    ));
    $this->add($email);
    ....

Example 2 (for Validation instance)

            ...
    $this->add ( 'email', new PresenceOf ( ['message' => 'Message 1'
    ] ) );

    $this->add ( 'email', new Email ( [
            'message' => 'Message 2'
    ] ) );
    ...

So, let's say if i leave email input empty, validator echos both messages but i want that it echos only the first one wich have failed. "'cancelOnFail' => true" unfotunately cancel all next validations which is something i don't want. I just want to limit echoed messages from one data set.

Sorry for my english, i hope i was enought clear.

This seems very application specific issue.

Example straight from [the docs](https://docs.phalcon.io/en/3.2/forms)

if (!$form->isValid($_POST)) {
    $messages = $form->getMessages();

    foreach ($messages as $message) {
        echo $message, '<br>';
    }
}

You can just print first message in the array and break or something like that?



1.1k
Accepted
answer
edited Nov '17

I have already found a solution and it is very similar to yours :) thank you anyway. Here is how i did it...

        $v = new RegisterValidation ();
        $failed = $v->validate ( $this->request->getPost () );

        if (count ( $failed )) {
            foreach ( $v->getMessages () as $message ) {
                $errors [$message->getField ()] = $message;
            }
        } else {
        ...
        }