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

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()



41.3k
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.