Phalcon PHP 验证唯一性但允许空值
Phalcon PHP validation Uniqueness but allow empty values
我有以下验证:
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);
}
}
问题是如何允许传递空数据。
如果数据为空,我想保存在数据库 NULL 中;如果数据通过,我想保存为唯一值。
好的,我找到了使用 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"
]);
}
}
]));
你也可以这样做
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);
}
我有以下验证:
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);
}
}
问题是如何允许传递空数据。 如果数据为空,我想保存在数据库 NULL 中;如果数据通过,我想保存为唯一值。
好的,我找到了使用 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"
]);
}
}
]));
你也可以这样做
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);
}