Reputation: 182
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.
Upvotes: 0
Views: 794
Reputation: 1078
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);
}
Upvotes: 0
Reputation: 424
you can also do this
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);
}
Upvotes: 1
Reputation: 182
Ok, I found solution with 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"
]);
}
}
]));
Upvotes: 0