Validate For Invalid File Path in ASP.Net FileUpload control
Since the FileUpload control is editable by default, there may be a chance that user might type in the path instead of selecting the file using browse button. Because of this there are chances that the file path itself may be invalid. If the file path is invalid, it means that there are no file to save to server and it can be treated as invalid. To validate the file or file path uploaded by the user, we can use the following validation technique that uses custom validator control's server side validation and notify the user if the file is invalid.
The below code snippet will help us achieving it.
ASPX
<asp:FileUpload ID="fuFile" runat="server" />
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="fuFile"
ErrorMessage="File is invalid, please select a correct file!" OnServerValidate="FileValidate"></asp:CustomValidator>
CodeBehind
protected void FileValidate(object source, ServerValidateEventArgs args)
{
if (fuFile.HasFile)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
|