views:

60

answers:

4

This is a trivial question, but for some reason I am having trouble with it.

I have HTML for uploading a file such as the following.

 <input type="file" name="settings">

And all I need to do is check when the form is submitted that a value has been selected. I dont need help with the code for the form submission, I just need help since I am guessing you are unable to validate this as you would other form input fields such as text boxes.

I have tried doing things like...
var file = document.getElementById('settings').value;
if(file.length > 0 == false){
//give error messsage here

I know that there should be an easy fix for this but I cant quite figure it out.

Thanks

A: 
<input type="file" name="field_name" onchange="validate_file_format('field_name','allowed file format as comma separeated')"/>

Ex:
<input type="file" name="sitemap_doc" onchange="validate_file_format('sitemap_doc','doc,pdf')"/>


JS Code:
======
function validate_file_format(field_name, allowed_ext){
    obj1=document.req_form;
    var temp_field= 'obj1.'+field_name+'.value';
    field_value=eval(temp_field);
    if(field_value!=""){
        var file_ext= (field_value.substring((field_value.lastIndexOf('.')+1)).toLowerCase());
        ext=allowed_ext.split(',');
        var allow=0;
        for ( var i=0; i < ext.length; i++) {
                if(ext[i]==file_ext){
                    allow=1;
                }
        }
        if(!allow){
            alert('Invalid File format. Please upload file in '+allowed_ext+' format');        
            return false;
        }
    }
    return false;
} 
Joe Garrett
+1  A: 

You need to give the code an id attribute with the value "settings". You have a strange if construction.

if(file.length <= 0) { //error message }

Stijn Leenknegt
+3  A: 

I don't see why this would not work - as long as you give the input an id:

<input type="file" name="settings" id="settings">
Les Green
+1  A: 

What about just doing:

<input type="file" name="settings" id="settings">
George Marian