I am trying to validate a file upload as below using a custom validation rule but its not working.
class JFormRuleResume extends JFormRule
{
public function test(&$element, $value, $group = null, &$input = null, &$form = null)
{
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
$jinput = JFactory::getApplication()->input;
$fileInput = new JInput($_FILES);
$file = $fileInput->get('jform', null, 'files', 'array');
//$files = $jinput->files->get('jform');
//$file = $files['resume'];
$filename = JFile::makeSafe($file['name']['resume']);
$filesize = $file['size'];
if (strtolower(JFile::getExt($filename))!='pdf') {
$element->addAttribute('message', strtolower(JFile::getExt($filename)));
return false;
}
if($filesize<2000000){
$element->addAttribute('message', "File size bigger than 2MB");
return false;
}
//var_dump($files);
return true;
}
}
Whether I upload a pdf file or other files with different extension, the error "Invalid file type" is returned.
Please enlighten me what the problem is?
My field looks like this:
<field
name="resume"
type="file"
label="Resume"
description=""
size="40"
accept="application/pdf"
validate="resume"
required="true"
/>
UPDATE
This is an update to what i've discovered so far. The post data
$requestData = JRequest::getVar('jform', null, 'post', 'array');
do not fetch the file input value. It is therefore, i've to add the following code in the controller action before i validate the form $data = $model->validate($form, $requestData);
$requestData = JRequest::getVar('jform', null, 'post', 'array');
// Get the file data array from the request.
$jinput = JFactory::getApplication()->input;
$fileInput = new JInput($_FILES);
$file = $fileInput->get('jform', null, 'files', 'array');
// Make the file name safe.
$filename = JFile::makeSafe($file['name']['resume']);
$requestData['resume'] = strtolower($filename);
JRequest::setVar('jform', $requestData );
$form = $model->getForm();
if (!$form) {
JError::raiseError(500, $model->getError());
return false;
}
$data = $model->validate($form, $requestData);
This way i am able to inject the file input value to the post array. But the problem still lies somewhere because the above validation works only partially. The validation works correctly only for files like docx, png, htm, php, txt .... and if i submit doc, pdf (larger than 2MB), zip files the validation do not work at all, instead i am displayed back the form without data and with the validation warning that all the fields are missing.
This is very strange, i desperately need some help.
JFile::getExt($filename)
returns? My guess is, something on the way (i.e.$filename
,$file
or$fileInput
) is not what you expect. – Markus Malkuschvar_dump(JFile::getExt($filename));
? Also, change!=
to!==
– Loddervar_dump('test');
just beforereturn true;
and if you don't see anything, I think I might know what the problem is. – Lodder