Wednesday 16 April 2014

How to validate file upload control Extension using JQuery in ASP.NET


In this article I will explain how to validate file upload control extension using JQuery in ASP.NET.

In this scenario user can upload different type of files using file upload control. We validate to allow only image file. Below is the sample JQuery code for validating file extension.

JQuery code:

<script type="text/javascript">
$(function () {
$('#<%=fuFileExtension.ClientID %>').change(function () {
var fileExtension = ['png', 'jpeg', 'jpg', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only allow '.png','.jpeg','.jpg', '.gif', '.bmp'.");
}
else
{
alert("Accepted");
}
})
})
</script>


Below is the total page design

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
$('#<%=fuFileExtension.ClientID %>').change(function () {
var fileExtension = ['png', 'jpeg', 'jpg', 'gif', 'bmp'];
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only allow '.png','.jpeg','.jpg', '.gif', '.bmp'.");
}
else
{
alert("Accepted");
}
})
})
</script>
</head>
<body>
<form id="fFileExtension" runat="server">
<table align="Center">
<tr>
<td colspan="2" style="font-size: large;"><b><u>Validate fileupload control using jquery</u></b>
</td>
</tr>
<tr>
<td colspan="2" height="20px"></td>
</tr>
<tr>
<td><b>Upload Images:</b></td>
<td>
<asp:FileUpload ID="fuFileExtension" runat="server" /></td>
</tr>
</table>
</form>
</body>

</html>

Output:


No comments:

Post a Comment