Conditional Validation in Model

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.

You can use conditional rules.

https://book.cakephp.org/3/en/orm/validation.html#using-conditional-rules

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)

@sneha, conditional validation is what you need, @coreytaylor just linked to the wrong page :slight_smile:

https://book.cakephp.org/3/en/core-libraries/validation.html#conditional-validation

Yes, thank you. I was stuck on the wrong validation.

@dakota ,Thanx, it worked. :star_struck: