0

I have a UserControl (with FileUpload) included on a Master Page as follows:

Master Page

 <uc:uploadFiles ID="UC1" runat="server"/>

uploadFiles.ascx

<script type="text/javascript">
function ValidateUpload() {
    var FileUpload_function = document.getElementById('myfile');

    if (FileUpload_function.value == '') {
        return false;
    }
    else {
        //do stuff        }
    return true;
}
</script>

<div id="div_FileUpload" class="FileUpload_content" runat="server">
    <asp:FileUpload ID="myfile" class="FileUpload" runat="server" />
    <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="myfile" ClientValidationFunction="ValidateUpload" />
</div>

When I run the page I get the following error caused by the CustomValidator: Unable to get property 'value' of undefined or null reference.

My guess is that the FileUpload value is validated before the entire page is rendered because when I delete the UserControl and move the codes to the MasterPage directly, the CustomValidator works fine.

How can I solve the problem?

Gloria
  • 1,305
  • 5
  • 22
  • 57
  • You have to look for generated html. Make sure id of control remain same when you see in browser. http://stackoverflow.com/questions/10045419/validate-asp-fileupload-control-client-side – dotnetstep Nov 26 '14 at 07:26
  • Like @dotnetstep is saying check the id of the fileupload, there will be a prefix before the `myfile` – Mivaweb Nov 26 '14 at 07:27

1 Answers1

1

You need to use .ClientID in document.getElementById. Becasue when you use that in user control, cotnrol id - myfile might be renamed to something else, like ct00_myfile and in that case if you execute same js code, it will give you null.

You need to use following js code.

var FileUpload_function = document.getElementById('<%=myfile.ClientID %>');

Arindam Nayak
  • 7,346
  • 4
  • 32
  • 48