File type validation in Joomla component


If we want to validate file types when user choose a file for a specific file field. like image field will accept only files which has “.jpg, .jpeg, .png, .bmp ” extension. and for pdf file field will allow only “.pdf” files extension otherwise deselect the wrong selected file and reset the file field.

<?php
JHTML::_('behavior.mootools');
//add jquery file path to component
$doc = JFactory::getDocument();
$doc->addScript(JURI::root(true) . '/components/com_test/includes/javascript/jquery-1.8.3.js');
//add file validation code and bind then on change event
$doc->addScriptDeclaration('
$(document).ready(function(){
//for zip file
$("#file_zip").bind("change", function() {

var fileName = $("#file_zip").val().toLowerCase();
var ext = fileName.split(\'.\').pop();

if(ext!=\'zip\'){
alert(\'Please upload only zip file\');
$("#file_zip").val("");
return false;
//For IE
//$("#file_zip").replaceWith($("#file_zip").clone(true));
//For other browsers
//$("#file_zip").val("");
}
});

//for pdf file
$("#file_pdf").bind("change", function() {
var fileName = $("#file_pdf").val().toLowerCase();
var ext = fileName.split(\'.\').pop();
if(ext!=\'pdf\'){
alert(\'Please upload only pdf file\');
$("#file_pdf").val("");
return false;
}
});

//file_image
$("#file_image").bind("change", function() {
var fileName = $("#file_image").val().toLowerCase();
var ext = fileName.split(".").pop();
//alert(fileName.split(".").pop());
if( ext!="jpg" && ext!="jpeg" && ext!="png" && ext!="bmp" ){
alert("Please upload only image file");
$("#file_image").val("");
return false;
}
});

});

');
?>
<form enctype="multipart/form-data" method="post" action="index.php" name="form">
<input type="file" id="file_zip" name="file_zip">
<input type="file" id="file_pdf" name="file_pdf">
<input type="file" id="file_image" name="file_image">
<input type="submit">
</form>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s