Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.phalconphp.com/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?



440
Accepted
answer
edited 18d ago

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 {
        ...
        }