Conditional Validation in Model

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.

->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.


You can use conditional rules.

This doesn’t help.

My exact code is :
->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().

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:

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

@dakota ,Thanx, it worked. :star_struck: