Click here to Skip to main content
Click here to Skip to main content

YaldaValidation For FileUpload Control

, 11 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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:

<%@ 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

<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

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).

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

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

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.

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)

About the Author

taha bahrami
Web Developer
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.
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionFrame Work 3.5 PinmemberAli Ejaz8-Jun-12 2:38 
AnswerRe: Frame Work 3.5 Pinmembertaha bahrami8-Jun-12 6:01 
GeneralRe: Frame Work 3.5 PinmemberAli Ejaz8-Jun-12 6:53 
GeneralRe: Frame Work 3.5 Pinmembertaha bahrami8-Jun-12 9:49 
GeneralRe: Frame Work 3.5 PinmemberAli Ejaz11-Jun-12 0:42 
AnswerRe: Frame Work 3.5 Pinmembertaha bahrami11-Jun-12 1:15 
GeneralRe: Frame Work 3.5 PinmemberAli Ejaz11-Jun-12 1:24 
GeneralRe: Frame Work 3.5 PinmemberAli Ejaz11-Jun-12 1:36 
AnswerRe: Frame Work 3.5 Pinmembertaha bahrami11-Jun-12 16:34 
GeneralMy vote of 5 Pinmembernairika vakili31-May-12 2:12 
GeneralRe: My vote of 5 Pinmembertaha bahrami31-May-12 2:15 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 11 Jun 2012
Article Copyright 2012 by taha bahrami
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid