Wednesday, February 10, 2010

Javascript : Validate file upload

Javascript code:

<script language="javascript">
function Checkfiles()
var fup = document.getElementById('upload_filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc")
return true;
alert("Upload Gif or Jpg images only");
return false;

HTML form:

<form action="#" enctype="multipart/form-data" method="POST" onsubmit="return Checkfiles();">
<input type="file" id="upload_filename">
<input type="submit" value="Go!">

Or Ruby on Rails form:

<% form_for(@upload, :html => {:multipart => true, :onsubmit=>"return Checkfiles();"}) do |f| %>
<%= f.file_field :filename %>
<%= f.submit 'Create' %>
<% end %>

If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)


  1. when i put a file with allowed extension it still gives me the same error

  2. How about if my fileupload type is in the content place ? any idea ?

  3. Thanks for the Good Script, but can u give me the code for clearing Uploading image path, if it was not a valid extension.

    Thanks in Advance.

  4. Hey Thanks for your code but it is not working for me..
    can your update your code...