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

Use multiple column on validator interface with multiple message

Hello, I'd like to know if it is possible to do this :

     public function validation()
     {
         // Name required
         $this->validate(new PresenceOf(
             [
                 'field'   => ['columnA', 'columnB', 'columnC'],
                 'message' => [
                     'The columnA is required',
                    'The columnB is required',
                    'The columnC is required'
                ]
             ]
         ));

On different validator interface. I don't see anything about it on the doc but I know this is possible to pass an array of column to 'field' for the EmailValidator

Cheer,



145.0k
Accepted
answer
edited May '15

I guess you can always write your custom validator :)

I wrote something like this:

    class MultiplePresenceOf extends Validator implements ValidatorInterface
{
    public function validate(ModelInterface $record)
    {
        $messages = $this->getOption("message");
        $fields = $this->getOption("field");
        $wasEmpty = true;
        foreach ($fields as $field) {
            $value = $record->$field;
            if (empty($value)) {
                $this->appendMessage($messages[$field], $field);
                $wasEmpty=false;
            }
        }
        return $wasEmpty;
    }
}

Interesting, thanks !

I'm always looking for a native solution if it exists

I guess you can always write your custom validator :)

I wrote something like this:

   class MultiplePresenceOf extends Validator implements ValidatorInterface
{
   public function validate(ModelInterface $record)
   {
       $messages = $this->getOption("message");
       $fields = $this->getOption("field");
       $wasEmpty = true;
       foreach ($fields as $field) {
           $value = $record->$field;
           if (empty($value)) {
               $this->appendMessage($messages[$field], $field);
               $wasEmpty=false;
           }
       }
       return $wasEmpty;
   }
}