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 in model

All data from the form I send using Ajax. And validation of the fields I pass on the server. Here is a typical example:

public function registrationAjaxAction()
    {
        $account = new Account();

        if ($validation = $account->validateRegistrationData($_POST)) {
            return $this->response
                ->setJsonContent(array('validation' => $validation));
        }

        if ($account->registration($_POST)) {
            return $this->response
                ->setJsonContent(array('redirect' => '/account'));
        } else {
            return $this->response
                ->setJsonContent(array('alert' => array('type' => 'error', 'text' => 'Server error')));
        }
    }

Error validation must come an array where the key is the field name and the value is the error text. Here is an example of the validation:

public function validateRegistrationData($attributes)
    {
        $validation = new Validation();

        $validation->add('login', new PresenceOf(array(
            'message' => 'Введите логин'
        )));
        $validation->add('email', new PresenceOf(array(
            'message' => 'Введите электронный адрес'
        )));
        $validation->add('email', new Email(array(
            'message' => 'Не верный формат'
        )));
        $validation->add('password', new Confirmation(array(
            'message' => 'Пароли должны совпадать',
            'with' => 'confirm_password'
        )));

        $messages = $validation->validate($attributes);
        if (count($messages)) {
            foreach ($messages as $message) {
                 $errors[$message->getField()] = $message->getMessage();
            }
            return $errors;
        } else {
            return false;
        }
    }

In this situation, I don't know how to check for the uniqueness of the username and email. As far as I know, the standard validator is not able to do it. Maybe someday this can be done by means of the validation of the model? If be conducted through the model, the name of the html form is lost.

public function validation()
    {
        $this->validate(new Email(array(
            'field' => 'email'
        )));
        $this->validate(new Uniqueness(array(
            'field' => 'email',
            'message' => 'Этот адрес уже используется'
        )));
        $this->validate(new Uniqueness(array(
            'field' => 'username',
            'message' => 'Это имя уже используется'
        )));

        if ($this->validationHasFailed()) {
            return false;
        }
    }

Sorry for my English.

Валидация на уникальность работает, отсортировать по полям реально, и без костылей.

Models/User.php

<?php
    // Users.php
    public function validation() {

        // Validating username on uniqueness
        $this->validate(new \Phalcon\Mvc\Model\Validator\Uniqueness(array(
            'field' => 'username',
            'message' => 'Данный логин уже зарегистрирован в системе.'
        )));

        // False, if validation failed, true if validation completed successfully
        return $this->validationHasFailed() != true;

    }

AjaxController::newUserAction()

if (!$user->save()) {

    // Oh, we've got errors!
    foreach ($user->getMessages() as $msg) {
        $this->flash->error($msg->getMessage());
    }

}

Dump $user->getMessages()

array (1)
0 => Phalcon\Mvc\Model\Message
    _type protected => "Unique" (6)
    _message protected => "Данный логин, уже зарегистрирован в системе." (81)
    _field protected => "username" (8)
    _model protected => NULL
    _code protected => 0