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 at Form Level not working, However validation at model level is working

I am having issues with the validation at the form level properly returning error messages.

The Following is my validation code at the form level. The form functions just fine, but the validation does not appear to throw any validation errors.

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Forms\Element\Select;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Email;

class UserForm extends Form
{
  public function initialize($entity = null, $options = null)
      {  
        ...

        $email = new Text('email', array( 'placeholder' => 'Email' ));
        $email->addValidators(array(
            new PresenceOf(array( 'message' => 'The e-mail is required')),
            new Email(array( 'message' => 'The e-mail is not valid' ))
        ));
        $this->add($email);
        ...
    }
}

If i put the validation at the model level. Validating this way returns the errors just fine.

class Users extends Model
{
    public function validation()
    {
        $this->validate( new Email(array(
            'field' => 'email',
            'message' => 'The email is invalid'
        )));

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

Am i missing the intended functionaliy of the form validators? do i need to return the errors at the form level as well?



51.2k
Accepted
answer

Your code looks fine. We could help if we see the logic of your action. it should be similar to this:

public function registerAction()
{
    if ($form->isValid()) {
        /// Do model insert/ validation
    } else {
        // Show form errors
    }
}