Joomla 4 Tips and Tricks: Form Validation File Size
From Joomla! Documentation
Introduction[edit]
This tip describes file upload size validation for components other than com_media. The relevant form element in the edit form from the code below looks like so:
The maximum upload size may be set by the hosting environment, see $upload_mb below, or set manually to an arbitrary limit, say 1Mb.
Setup Validation[edit]
The following code goes near the top of the form edit.php file. camp_infosheet is the javascript file containing the validation code, see below:
/** @var Joomla\CMS\WebAsset\WebAssetManager $wa */
$wa = $this->document->getWebAssetManager();
$wa->useScript('keepalive')
->useScript('form.validate')
->useScript('com_mycomponent.camp_infosheet');
$max_upload = (int)(ini_get('upload_max_filesize'));
$max_post = (int)(ini_get('post_max_size'));
$memory_limit = (int)(ini_get('memory_limit'));
$upload_mb = min($max_upload, $max_post, $memory_limit);
$doc = Factory::getDocument();
$doc->addScriptDeclaration("
var infosheet_size_max = '{$max_upload}';
");
And the following code goes in the body of the edit.php file. Notice the custom class validate-infosheet_size used to trigger validation:
<div class="controls">
<input
type="file"
name="jform[infosheet]"
id="jform_infosheet"
class="form-control w20rem required validate-infosheet_size"
accept="text/plain,application/msword,text/rtf,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.oasis.opendocument.text"
/><br>
Maximum upload size: <strong><?php echo $max_upload; ?>Mb</strong>
</div>
Javascript[edit]
This is the content of the validation script file:
document.addEventListener('DOMContentLoaded', (event) => {
document.formvalidator.setHandler('infosheet_size', function(value) {
return infosheet_size();
});
});
function infosheet_size () {
var infosheet = document.getElementById('jform_infosheet');
if (infosheet.files.length == 0) {
return false;
}
// check the size
var size = infosheet.files[0].size;
if (size > (infosheet_size_max * 1024 * 1024)) {
alert('This file is too big! Size = ' + size);
return false;
}
return true;
}
Result[edit]
Select a file larger than 2Mb in this case and there is an alert dialog and then this.