Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7587831
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T19:46:33+00:00 2026-05-30T19:46:33+00:00

I’m currently creating some custom attributes for doing uploaded file validation. One of which

  • 0

I’m currently creating some custom attributes for doing uploaded file validation.

One of which is a FileSizeAttribute to enforce certain limits (e.g. cannot be bigger than x bytes or smaller than y bytes).

Is there any way I can access the ContentLength property of the HttpPostedFileBase? I was reading a tutorial on file extension validation and the author showed some sample code for simply validating the file extensions.

I’d like to extend to validating the file size client side (in addition to server side) so I can tell them before they even upload if it’s outside of the size limits.

From the code snippet available, it seems like he has access to only the filename:

jQuery.validator.addMethod("fileextensions", function (value, element, param) {
    var extension = getFileExtension(value).toLowerCase();
    var validExtension = $.inArray(extension, param.fileextensions) !== -1;
    return validExtension;
});

Am I wrong here or am I just missing something? I’ve never used jQuery and I have a cursory knowledge of JavaScript, so I don’t really know if this is even possible.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T19:46:33+00:00Added an answer on May 30, 2026 at 7:46 pm

    This could be done if the browser supports the File API. It’s a simple matter of querying the size property.

    Here’s an example:

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class FileExtensionsAttribute : ValidationAttribute, IClientValidatable
    {
        private List<string> ValidExtensions { get; set; }
        public int MaxContentLength { get; set; }
    
        public FileExtensionsAttribute(string fileExtensions)
        {
            ValidExtensions = fileExtensions.Split('|').ToList();
        }
    
        public override bool IsValid(object value)
        {
            HttpPostedFileBase file = value as HttpPostedFileBase;
            if (file != null)
            {
                var fileName = file.FileName;
                var isValidExtension = ValidExtensions.Any(y => fileName.EndsWith(y));
                var isValidContentLength = file.ContentLength < MaxContentLength;
                return isValidExtension && isValidContentLength;
            }
            return true;
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ValidationType = "file";
            rule.ErrorMessage = this.FormatErrorMessage(ErrorMessage);
            rule.ValidationParameters["fileextensions"] = string.Join(",", ValidExtensions);
            rule.ValidationParameters["maxcontentlength"] = MaxContentLength.ToString();
            yield return rule;
        }
    }
    

    Model:

    public class MyViewModel
    {
        [FileExtensions("txt|doc", MaxContentLength = 200000)]
        public HttpPostedFileBase File { get; set; }
    }
    

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    

    View:

    @model MyViewModel
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        (function ($) {
            var getFileExtension = function (fileName) {
                var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
                if (extension != undefined) {
                    return extension[0];
                }
                return extension;
            };
    
            var getFileSize = function (fileElement) {
                if (fileElement.files && fileElement.files.length > 0) {
                    return fileElement.files[0].size;
                }
                return -1;
            };
    
            $.validator.unobtrusive.adapters.add(
                'file', ['fileextensions', 'maxcontentlength'], function (options) {
                    var params = {
                        fileextensions: options.params.fileextensions.split(','),
                        maxcontentlength: options.params.maxcontentlength
                    };
                    options.rules['file'] = params;
                    if (options.message) {
                        options.messages['file'] = options.message;
                    }
                }
            );
    
            $.validator.addMethod('file', function (value, element, params) {
                var extension = getFileExtension(value);
                var validExtension = $.inArray(extension, params.fileextensions) !== -1;
                var fileSize = getFileSize(element);
                return validExtension && fileSize < parseInt(params.maxcontentlength);
            }, '');
    
        })(jQuery);
    </script>
    
    @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.LabelFor(x => x.File)
        @Html.EditorFor(x => x.File)
        @Html.ValidationMessageFor(x => x.File)
        <button type="submit">OK</button>
    }
    

    Editor template (~/Views/Shared/EditorTemplates/HttpPostedFileBase):

    @model HttpPostedFileBase
    @Html.TextBoxFor(model => model, new { type = "file" })
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I want use html5's new tag to play a wav file (currently only supported
I would like to run a str_replace or preg_replace which looks for certain words
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.