sneha
October 21, 2019, 1:19pm
1
Hi,
In my Model, I need conditional validation. I want to run the validator rule for a particular field if the field is not empty and in case the field is empty the validator should not check the validation rules.
$validator
->add(‘document’, [
[ ‘rule’ => [‘extension’,[‘pdf’,‘jpg’,‘jpeg’,‘png’]], // default [‘gif’, ‘jpeg’, ‘png’, ‘jpg’]
‘message’ => __(‘Only pdf/jpg/jpeg/png files are allowed.’)]]);
i want this to be checked only in case the field has some value else bypass.
Thanks.
sneha
November 7, 2019, 6:37am
3
This doesn’t help.
My exact code is :
$validator
->requirePresence(‘document’, ‘create’)
->add(‘document’, [
[ ‘rule’ => [‘extension’,[‘pdf’,‘jpg’,‘jpeg’,‘png’]], // default [‘gif’, ‘jpeg’, ‘png’, ‘jpg’]
‘message’ => __(‘Only pdf/jpg/jpeg/png files are allowed.’)],
[‘rule’ => [‘fileSize’, ‘<=’, ‘2MB’],
‘message’ => __(‘File must be less than 2MB’)],
[‘rule’ => [‘mimeType’, [‘application/pdf’, ‘image/png’, ‘image/jpg’, ‘image/jpeg’]],
‘message’ => __(‘File Type must application/image.’)]
]
);
I want that this validator only works in case my field is not empty, else if empty it should bypass the validation.
If conditional rules won’t work for you, you can disable the rules check when calling Table::save()
.
https://api.cakephp.org/3.8/class-Cake.ORM.Table.html#_save
checkRules: Whether or not to check the rules on entity before saving, if the checking fails, it will abort the save operation. (default:true)
dakota
November 11, 2019, 11:10am
5
Yes, thank you. I was stuck on the wrong validation.
sneha
December 5, 2019, 5:54am
8
@dakota ,Thanx, it worked.