使用javascript验证input type =“file”字段

时间:2013-08-26 06:42:55

标签: javascript

我有一个表单,用户首先选择是否要上传任何文件。如果是,则向他们显示3个上传框。

点击提交后,有一个JavaScript函数可以检查任何空字段。在此功能中,如果选择了上传文件选项,那么我正在检查输入类型=“文件”是否为空。

我面临的错误是,即使用户选择要上传的文件,仍会显示上传文件的错误消息。

这是我的HTML代码:

<!-- 3rd Fieldset STARTS -->
<fieldset class="fieldSetSpace">
    <legend class="legendText">&nbsp; Upload Documents &nbsp;</legend>

    <span id="yes"><input type="radio" name="rdoUploadDocu" id="rdoUploadDocuYes" tabindex="23" value="yes" onClick="javascript: showUploadDiv();" /></span>
    &nbsp;Yes I have A Documents To Upload

    <div id="divUploadDoc" style="display:none;">
        <span class="contact_table">Upload Document 1 </span>

        <input type="file" name="files[]" id="file1" class="txtCoName" />

        <span class="contact_table">Upload Document 2</span>

        <input type="file" name="files[]" id="file2" class="txtCoName" />

        <span class="contact_table">Upload Document 3</span>

        <input type="file" name="files[]" id="file3" class="txtCoName" />
    </div>
    <?php echo $errorResumeUpload; ?>
    <br />
    <span id="no"><input type="radio" name="rdoUploadDocu" id="rdoUploadDocuNo" value="no" tabindex="24" onClick="javascript: hideUploadDiv();" /></span>
    &nbsp;No I do not have A Documents To Upload

    <div id="divUploadCheckError" class="divError"></div>

</fieldset>         
<!-- 3rd Fieldset ENDS -->

这是我的JS功能:

else if (document.getElementById('rdoUploadDocuYes').checked) 
{       
    var upload1 =  document.getElementById('file1').value;
    var upload2 =  document.getElementById('file2').value;
    var upload3 =  document.getElementById('file3').value;

    alert( upload1 );
    alert( upload2 );
    alert( upload3 );

    if( ( upload1 == '' ) || ( upload2 == '' ) || ( upload3 == '' ) )
    {
        var objErrDiv = document.getElementById('divUploadCheckError');
        objErrDiv.innerHTML= 'Please upload at least one documents ';
        objErrDiv.style.padding='4px 4px';
        objErrDiv.style.visibility='visible';
        objErrDiv.style.margin='10px 0px 2px 0px';
        return false;
    }
    else
    {
        return false;
    }
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

我认为您错过重置innerHTML div objErrDiv

else if (document.getElementById('rdoUploadDocuYes').checked) 
{       
    var upload1 =  document.getElementById('file1').value;
    var upload2 =  document.getElementById('file2').value;
    var upload3 =  document.getElementById('file3').value;
    var objErrDiv = document.getElementById('divUploadCheckError');

    alert( upload1 );
    alert( upload2 );
    alert( upload3 );

    if( upload1 == '' )
    {

        objErrDiv.innerHTML= 'Please upload at least one documents ';
        objErrDiv.style.padding='4px 4px';
        objErrDiv.style.visibility='visible';
        objErrDiv.style.margin='10px 0px 2px 0px';
        return false;
    }
    else
    {
        objErrDiv.innerHTML="";  // Try adding this
        return false;
    }
}