Is it possible to validate against more than one field with Phalcon\Validation?

Phalcon\Mvc\Model\Validator\Uniqueness can validate against an array of fields but Phalcon\Validation\Validator\Uniqueness appears to be unable to do this. Is there a solution to validating a record against an array of fields with the Phalcon\Validation approach?

As of source on github - no it is not possible now.



46.8k

I was also looking at the source and I'm thinking that perhaps an also option could be added to add in additional fields. It would function in a similar way to that of the except option but it would not negate the condition. This new Phalcon\Validation method is overall a lot nicer but it its configuration style doesn't really fit the needs of the Uniqueness validator. I think that it should be possible to pass in null for the field name so that proper setup can be performed using the more flexible options.



36.4k

I think you can use simple code like:

public function validation()
    {

        // $this->validate(
        //     new Email(
        //         array(
        //             'field'    => 'email',
        //             'required' => true,
        //         )
        //     )
        // );
        $this->validate(
            new Uniqueness(
                [
                    "field"   => array('email'),
                    "message" => "Another user with same email already exists."
                ]
            )
        );
        $this->validate(
            new Uniqueness(
                [
                    "field"   => array('username'),
                    "message" => "Another user with same username already exists."
                ]
            )
        );
        if ($this->validationHasFailed() == true) {
            return false;
        }
    }

Sure this works, but if you want

'field' => array('product', 'type')

it will not work in 2.1 if you use Validation\Validator\Uniqueness



46.8k

@Thien using two seperate Uniqueness validators is not the same thing as using a single one with two fields. In the case of a field array it is an AND operand and with two validators it is like and OR operand.

Simply the new validation doesn't support this yet. However it can be easily recreated with a simple PHQL query and so for now I'm doing this instead. So this means that a FIXME has graduated to a TODO.