none
FileUpload添加必填验证 RRS feed

答案

  • 你好,

    你可以使用RequiredFieldValidator控件,例如:

    <asp:FileUpload ID="FileUpload1" runat="server" />
    
    <br />
    
    <asp:RequiredFieldValidator ErrorMessage="Required" ControlToValidate="FileUpload1"
    
        runat="server" Display="Dynamic" ForeColor="Red" />
    
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$"
    
        ControlToValidate="FileUpload1" runat="server" ForeColor="Red" ErrorMessage="Please select a valid Word or PDF File file."
    
        Display="Dynamic" />
    
    <br />
    
    <asp:Button Text="Submit" runat="server" />

    另外你也可以使用JQuery添加验证。

    <script type ="text/javascript">
    
        var validFilesTypes=["bmp","gif","png","jpg","jpeg","doc","xls"];
    
        function ValidateFile()
    
        {
    
          var file = document.getElementById("<%=FileUpload1.ClientID%>"); 
    
          var label = document.getElementById("<%=Label1.ClientID%>"); 
    
          var path = file.value;
    
          var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();
    
          var isValidFile = false;
    
          for (var i=0; i<validFilesTypes.length; i++)
    
          { 
    
            if (ext==validFilesTypes[i]) 
    
            {
    
                isValidFile=true;
    
                break;
    
            }
    
          }
    
          if (!isValidFile)
    
          {
    
            label.style.color="red";
    
            label.innerHTML="Invalid File. Please upload a File with" + 
    
             " extension:\n\n"+validFilesTypes.join(", ");
    
          }
    
          return isValidFile;
    
         }
    
    </script>
    
    
    <asp:FileUpload ID="FileUpload1" runat="server" />
    
    <asp:Button ID="btnUpload" runat="server" Text="Upload"  
    
       OnClientClick = "return ValidateFile()"  OnClick="btnUpload_Click"  />
    
    <br />
    
    <asp:Label ID="Label1" runat="server" Text="" />
    
    

    更多详细信息,请参考下面的链接:

    http://www.aspsnippets.com/Articles/ASPNet-FileUpload-File-Extension-Validation.aspx

    http://www.aspsnippets.com/Articles/Validate-FileUpload-Control-using-Regular-Expression-and-RegularExpression-Validator-in-ASPNet.aspx


    • 已标记为答案 lctk 2015年11月17日 7:55
    2015年11月17日 5:58
    版主