Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

YaldaValidation For FileUpload Control

11 Jun 2012CPOL2 min read 27.1K   170  
A custom validation control for FileUpload controls that validate like required validator, and have two more methods for extensions and file size!

Introduction

Validate the Extionsions that you need and the size of the upload file with YaldaValidation!!!

This validation control named "YaldaValidation" is a custom validation control that gets the job easily for those working with file upload. It is quiet simple and easy to use.

How to use 

Just add the C# class to your App_Code folder. Look at this code snippet:

C#
<%@ Register TagPrefix="custom" Namespace="testproject.App_Code" Assembly="App_Code" %>

You have to register this custom validator (if you just paste this below code it will ask you to generate automatically the register declare).

the YaldaValidation

ASP.NET
<custom:YaldaValidator ControlToValidate="FileUpload1" 
    Display="Dynamic" Extensions="jpeg+png" runat="server"
    SizeOfTheFileInKb="100" ErrorMessage="*"> 
</custom:YaldaValidator>

This validation has the same attributes of base validation, but there are two more attributes that make it useful for me!

First is Extensions: you put your extensions here and leave a + between the extension names!

Second is SizeOfTheFileInKb: you set the file size in KB and if the uploaded file is bigger than that, the validator causes a validation error!

How It Works

I create a new validation control by deriving a new control from the BaseValidator class. This is the base class for all validation controls.

basevalidator is a MustInherit (abstract) class, which requires to implement a single method: EvaluateIsValid => Returns true when the form field being validated is valid.

You just need to override this method.

My YaldaValidator.cs class code

C#
using System.Linq;
using System.Web.UI.WebControls;
namespace testproject.App_Code
{ 
    /// <summary>
    /// validate the file extension, size, and exists of a file in FileUpload Control
    /// </summary>
    public class YaldaValidator : BaseValidator
    {
        string _extensions = "";
        public string Extensions
        {
            get { return _extensions; }
            set { _extensions = value; }
        }
 
        int _sizeOfTheFileInKb = 1;
        public int SizeOfTheFileInKb
        {
            get { return _sizeOfTheFileInKb; }
            set { _sizeOfTheFileInKb = value; }
        }
        protected override bool EvaluateIsValid()
        {
            FileUpload fu = (FileUpload)FindControl(this.ControlToValidate);            
            string[] ex = _extensions.Split('+');
            if (fu.HasFile && fu.PostedFile.ContentLength <= _sizeOfTheFileInKb * 
                1024 && ex.Contains(System.IO.Path.GetExtension(fu.PostedFile.FileName).Substring(1)))
            { 
                return true; 
            } 
            else 
            {
                return false; 
            } 
        } 
    } 
}

Code Explanation

I get the extensions as a string set it to _Extensions. And I get the file size as int in kb an set to _SizeOfTheFileInKb. In the EvaluateIsValid() method I find the FileUpload control (get ID by this.ControlToValidate).

C#
FileUpload fu = (FileUpload)FindControl(this.ControlToValidate);

Then make the string into a array of strings using the .Split() method.

C#
string[] ex = _extensions.Split('+');

In the if clause, I check if the file exists using the .HasFile() method, and then compare the size of the existing file with the valid size (it's a multiple of 1024 because it's in KB).

At last check the file extension with one of the given extension names.

C#
if (fu.HasFile && fu.PostedFile.ContentLength <= _sizeOfTheFileInKb * 1024 && 
     ex.Contains(System.IO.Path.GetExtension(fu.PostedFile.FileName).Substring(1)))

If the conditions return true, you can upload your file.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)