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.

Add arrayof/multiple fields to new Phalcon\Validation\Validator?

Hi. If I got it righ, Phalcon\Mvc\Model\Validator will be deprecated in 2.1.0 and currently both old and new(Phalcon\Validation\Validator) can be used for model validation. Seem that prior to 2.0.8 it was possible to add multiple fields to validation that way:

$this -> validate(new Phalcon\Mvc\Model\Validator\Numericality([
            'field' => ['invoice_id','part_index','price','qty','discount','points'],
            'message' => 'This field should be numeric'
]));

How to achieve the same with new Phalcon\Validation\Validator?

Also currently I'm using 2.0.10 and I'm unable to pass array of fields neither to Phalcon\Mvc\Model\Validator\ (using 'field' or 'fields') nor to new $validator->add() method as first field parameter.

I got Phalcon exception for new method and old method with array assigned to field, or validation failure for correct values in case array assigned to fields.



6.3k
Accepted
answer
edited Mar '16

Ok. This code is working:

$validator->add(['part_number','part_description','price','qty','points','discount'],
        new PresenceOf([
            'message' => ':field is required'
        ]));

However in particular case with Numeric validator, which was renamed to \Phalcon\Validation\Validator\Digitsomething is wrong, cause this:

$validator ->add('qty',
        new DigitValidator([
            'message' => ':field must be numeric'
        ]));

returns

array (size=1)
  0 => 
    object(Phalcon\Mvc\Model\Message)[106]
      protected '_type' => string 'PresenceOf' (length=10)
      protected '_message' => string 'qty is required' (length=15)
      protected '_field' => string 'qty' (length=3)
      protected '_model' => null

for qty = 'string'.

Well. For old validation mechanism i implemented such a class:

use Phalcon\Mvc\EntityInterface;
use Phalcon\Mvc\Model\Validator;
use Phalcon\Mvc\Model\ValidatorInterface;
class MultiplePresenceOf extends Validator implements ValidatorInterface
{
    public function validate(EntityInterface $record)
    {
        $messages = $this->getOption("message");
        $fields = $this->getOption("field");
        $noError = true;
        foreach ($fields as $field) {
            $value = $record->readAttribute($field);
            if(is_object($value)){
                $noError=false;
            }
            else if (empty($value) && !is_numeric($value)) {
                $this->appendMessage($messages[$field], $field);
                $noError=false;
            }
            else if(!isset($value)){
                $this->appendMessage($messages[$field], $field);
                $noError=false;
            }
        }
        return $noError;
    }
}

Dont no how it should like for new validation mechanism.