Click here to Skip to main content
15,890,282 members
Articles / Web Development / ASP.NET
Tip/Trick

YaldaValidation For FileUpload Control

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
11 Jun 2012CPOL2 min read 26.5K   6   11
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)


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
Taha has started programming at the age of 16 and he has taken an avid interest in Microsoft technologies. He professionally works on ASP.NET and C#. Mainly, He lives for getting the world into codes and follows this aspiration in a third world country with lack of facility and support. He never gives up seeking success and competence.

Comments and Discussions

 
QuestionFrame Work 3.5 Pin
Ali Ejaz8-Jun-12 2:38
Ali Ejaz8-Jun-12 2:38 
AnswerRe: Frame Work 3.5 Pin
taha bahraminezhad Jooneghani8-Jun-12 6:01
taha bahraminezhad Jooneghani8-Jun-12 6:01 
did you try it in 3.5?
I work out to find a soloution for you!
GeneralRe: Frame Work 3.5 Pin
Ali Ejaz8-Jun-12 6:53
Ali Ejaz8-Jun-12 6:53 
GeneralRe: Frame Work 3.5 Pin
taha bahraminezhad Jooneghani8-Jun-12 9:49
taha bahraminezhad Jooneghani8-Jun-12 9:49 
GeneralRe: Frame Work 3.5 Pin
Ali Ejaz11-Jun-12 0:42
Ali Ejaz11-Jun-12 0:42 
AnswerRe: Frame Work 3.5 Pin
taha bahraminezhad Jooneghani11-Jun-12 1:15
taha bahraminezhad Jooneghani11-Jun-12 1:15 
GeneralRe: Frame Work 3.5 Pin
Ali Ejaz11-Jun-12 1:24
Ali Ejaz11-Jun-12 1:24 
GeneralRe: Frame Work 3.5 Pin
Ali Ejaz11-Jun-12 1:36
Ali Ejaz11-Jun-12 1:36 
AnswerRe: Frame Work 3.5 Pin
taha bahraminezhad Jooneghani11-Jun-12 16:34
taha bahraminezhad Jooneghani11-Jun-12 16:34 
GeneralMy vote of 5 Pin
nairika vakili31-May-12 2:12
nairika vakili31-May-12 2:12 
GeneralRe: My vote of 5 Pin
taha bahraminezhad Jooneghani31-May-12 2:15
taha bahraminezhad Jooneghani31-May-12 2:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.