Phalcon PHP验证唯一性,但允许为空值

时间:2019-03-29 09:45:12

标签: php validation phalcon phalcon-orm

我有以下验证:

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);
    }
}

问题是如何允许传递空数据。 如果数据为空,则我希望将其保存在数据库中,如果传递则为唯一值。

2 个答案:

答案 0 :(得分:1)

您也可以这样做

public function validation()
{
    $validator = new Validation();

    if (!empty($this->getSomeData())) {
        $validator->add('some_data', new Uniqueness([
            'message' => 'this field must be unique or epmty'
        ]));
    }
    // some other rules (...)
    return $this->validate($validator);
}

答案 1 :(得分:0)

好的,我找到了CallbackValidator的解决方案


    $validator->add('some_data', new CallbackValidator([
                    "callback" => function($data) {
                        if (!empty($data->getSomeData())) {
                            return new Uniqueness([
                                "message" => "this field must be unique or epmty"
                            ]);
                        }
                    }
        ]));