Upload a file with required validation using jQuery






4.79/5 (7 votes)
Uploading a File with the required validation
Introduction
In this example, I will explain how to specify what file can be selected for uploading from
a FileUpload
control and until the
valid file is selected the Upload button would be disabled. The complete validation process would be
done with jQuery. And we will also see how to display a label instead of an alert message box.
Background
In many forums, I see the question of how to validate the required file using JavaScript or jQuery.
When you click on the Browse button, a window will be opened in the client side.
Select any file and click the Open button. If you selected only .Jpg or .JPEG files, the Upload button would be enabled. Try out with both, like select a .jpg file and check if you can see the Upload button. If you click any other file than a .jpg extension file, then you would see a message saying that “Only '.jpeg','.jpg' formats are allowed”.
Selecting a non .jpg extension:
Selecting a .jpg file:
Using the code
In the file extension we have taken only .jpg or .jpeg files and we are checking weather the selected file from fileupload is a .jpg or not? If it is not a .jpg or .jpeg then we are displaying a label message Only .jpg format is allowed. If it's a .jpg file then we are enabling the upload button.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#<%=fuPhoto.ClientID %>').change(
function () {
var fileExtension = ['jpeg', 'jpg'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
// alert("Only '.jpeg','.jpg' formats are allowed.");
$('#<%=btnUpload.ClientID %>').attr("disabled", true);
$('#<%= myLabel.ClientID %>').html("Only '.jpeg','.jpg' formats are allowed.");
}
else {
$('#<%=btnUpload.ClientID %>').attr("disabled", false);
$('#<%= myLabel.ClientID %>').html(" ");
}
})
})
</script>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fuPhoto" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" Enabled="false" />
<asp:Label ID="myLabel" runat="server" ForeColor="#CC0000" />
</div>
</form>
In the file extension, you can write your own extensions as per your requirements, like .gif, .doc, .ppt etc.