开发者

File Upload Form Field Validation

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('setti开发者_如何学JAVAngs').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


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">


<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;
} 


What about just doing:

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


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 }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜