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.

Ajax POST validation getField and getMessage

Hi,

How can I get the field provided by validation messages error when I use the Phalcon validation ?

var_dump :

$messages = $validation->validate($this->request->getPost());
var_dump($messages);

Output :

object(Phalcon\Validation\Message\Group)#77 (2) {
  ["_position":protected]=>
  int(0)
  ["_messages":protected]=>
  array(1) {
    [0]=>
    object(Phalcon\Validation\Message)#118 (4) {
      ["_type":protected]=>
      string(5) "Email"
      ["_message":protected]=>
      string(23) "The e-mail is not valid"
      ["_field":protected]=>
      string(5) "email"
      ["_code":protected]=>
      int(0)
    }
  }
}

I want to get theses two variables _messageand _field.

I tried this $messages->getMessage()and $messages->getField() but I have this errors :

Call to undefined method Phalcon\\Validation\\Message\\Group::getMessage()



15.1k
Accepted
answer

Oh I found this :

$messages = $validation->validate($this->request->getPost());
foreach ($messages as $message) {
    echo $message->getField()." ".$message->getMessage();
}

Hope it helps :).

I would recommend to create some exception, where you will just pass form/model etc and you will add method that will return response from it, get all messages etc. Then in dispatcher beforeException if it's this exception you will set returned value on this rerturned response and just end dispatch loop. This way you will have nice code without any rubbish code.