SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru DeNasio's Avatar
    Join Date
    May 2001
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Checking file extension

    Hello,

    I have seen many Javascripts on Internet that checks the extension of the file before uploading. But all these scripts checks the extension when the Submit button is pressed. I want to check the file extension as soon as the file is selected. The script should delete the selected file from the type=file box and display an error message (when a file with the wrong extension is selected). Can any one point me in the right direction how to achieve this?
    Ballot-Box.net - free polls for webmasters
    FormLog.com - free form processor

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is a crude lash-up that avoids alert boxes, which aren't too refined for the job. The triggering point and auto deletion are browser dependent. This example expects an '.htm' or '.html' extension:
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <title>Javascript Test</title>
    </head>
    <body>
    <p>
    <input type=file id='fs' ><span id='fWarn' style='color:#f00;font-weight:bold'></span>
    <script type="text/javascript">
    
    var fileBox = document.getElementById('fs');
    
    fileBox.onblur = checkExt;
    
    fileBox.onchange = function(){ this.onblur=null; checkExt(); }
    
    function checkExt()
    {   
     var warnBox = document.getElementById( 'fWarn' ), ext;
       
     if( /\S/.test( fileBox.value ) && !/\.html?$/i.test( fileBox.value ) )
     { 
      ext = fileBox.value.match(/\.[^\.]*$/) || "(none)" ;
      warnBox.innerHTML = 'Wrong file extension: ' + ext;
      fileBox.value = ''; 
     }
     else
      warnBox.innerHTML = '';
    }
    
    </script>
    </body>
    </html>
    Tab-indentation is a crime against humanity.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •