我使用的是CakePHP 3。我有上传字段,希望只允许上传.pdf和.doc(x)文件。如何将该属性添加到以下验证器?
$validator
->notEmpty('article');
只需在验证中添加扩展规则,该规则在http://api.cakephp.org/3.0/class-Cake.Validation.Validation.html
extension(string|array$check,array$extensions['gif','jpeg','png','jpg'])
示例:
$validator
->allowEmpty('profile_image')
->add('profile_image', [
'validExtension' => [
'rule' => ['extension',['png']], // default ['gif', 'jpeg', 'png', 'jpg']
'message' => __('These files extension are allowed: .png')
]
]);
您必须向验证器添加规则:
$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')
]);
使用allowEmpty('profile_image')可能会遇到一些问题,因为它是'file'类型的字段。
也许您最好查看带有可选true参数的uploadedFile规则。