问题
I am using CakePHP 3. I have the upload field and want to permit uploading only .pdf and .doc(x) files. How can I add that properties to the following validator?
$validator
->notEmpty('article');
回答1:
Simply add the extension rule in your validation which is define in http://api.cakephp.org/3.0/class-Cake.Validation.Validation.html
extension( string|array $check , array $extensions ['gif', 'jpeg', 'png', 'jpg'] )
example:
$validator
->allowEmpty('profile_image')
->add('profile_image', [
'validExtension' => [
'rule' => ['extension',['png']], // default ['gif', 'jpeg', 'png', 'jpg']
'message' => __('These files extension are allowed: .png')
]
]);
回答2:
You have to add rule to your validator:
$validator
->notEmpty('avatar', __('Please enter your cute picture'))
->requirePresence('avatar', 'create')
->add('avatar', 'validFormat', [
'rule' => ['custom', '([^\s]+(\.(?i)(pdf|doc|docx))$)'],
'message' => __('These files extension are allowed: .pdf, .doc, .docx')
]);
回答3:
Using allowEmpty('profile_image') might give you some issues since it's a field of type 'file'.
Maybe you better look at the uploadedFile rule with optional true parameter.
来源:https://stackoverflow.com/questions/33432934/cakephp-3-validation-of-uploaded-file-extension