phpvalidationphalconphalcon-orm

Phalcon PHP validation Uniqueness but allow empty values


I have the following validation:

use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;

class Users extends BaseModel {
    public function validation() {
        $validator = new Validation();
        $validator->add('some_data', new Uniqueness([
                    'message' => 'this field must be unique or epmty'
        ]));
        // some other rules (...)
        return $this->validate($validator);
    }
}

The question is how to allow pass empty data. I'd like to save in database NULL if data is empty or unique value if it's passed.


Solution

  • You should just be able to do the following in your model class:

    public function validation()
        {
            $validator = new Validation();
            $validator->add(
                'example',
                new Uniqueness(
                    [
                        'message' => 'Example must be unique',
                        'allowEmpty' => true,
                    ]
                )
            );
            return $this->validate($validator);
        }