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 8060069
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T09:52:05+00:00 2026-06-05T09:52:05+00:00

The basic question to start: How can you put a custom, unobtrusive validator ontop

  • 0

The basic question to start: How can you put a custom, unobtrusive validator ontop of a list of objects within your model? Like, say my model allows multiple file uploads, and thus I have a list of files, and I want my validator to run on each of those files?

Now for a specific example. I’ve got a custom, unobtrusive validator that checks to see if a file extension is not within a list of prohibited extensions:

public class FileExtensionValidatorAttribute : ValidationAttribute, IClientValidatable {

    protected static string[] PROHIBITED_EXTENSIONS = {
        // ... List of extensions I don't allow.
    };

    public override bool IsValid(object value) {
        if (value is IEnumerable<HttpPostedFileBase>) {
            foreach (var file in (IEnumerable<HttpPostedFileBase>)value) {
                var fileName = file.FileName;
                if (PROHIBITED_EXTENSIONS.Any(x => fileName.EndsWith(x))) return false;
            }
        } else {
            var file = (HttpPostedFileBase)value;
            var fileName = file.FileName;
            if (PROHIBITED_EXTENSIONS.Any(x => fileName.EndsWith(x))) return false;
        }

        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
        var modelClientVlidationRule = new ModelClientValidationRule {
            ErrorMessage = this.ErrorMessageString,
            ValidationType = "fileextension",
        };
        modelClientVlidationRule.ValidationParameters.Add("prohibitedextensions", string.Join("|", PROHIBITED_EXTENSIONS));

        yield return modelClientVlidationRule;
    }
}

Take note in my IsValid that I built this to accept a single file or a list of files.

In my model class, I can make use of this on a single HttpPostedFileBase:

[FileExtensionValidator(ErrorMessage = "Invalid Extension")]
public HttpPostedFileBase Upload { get; set; }

Then I attach to jquery’s validator in my view:

jQuery.validator.addMethod("fileExtension", function (value, element, param) {
    var extension = "";
    var dotIndex = value.lastIndexOf('.');
    if (dotIndex != -1) extension = value.substring(dotIndex + 1).toLowerCase();

    return $.inArray(extension, param.prohibitedExtensions) === -1;
});

jQuery.validator.unobtrusive.adapters.add('fileextension', ['prohibitedextensions'], function (options) {
    options.rules['fileExtension'] = {
        prohibitedExtensions: options.params.prohibitedextensions.split('|')
    };
    options.messages['fileExtension'] = options.message;
});

This all works great, client side and server side …but only on a single HttpPostedFileBase. The problem is that I need to provide users the ability to upload one or more files. If I change my model to this:

[FileExtensionValidator(ErrorMessage = "Invalid Extension")]
public List<HttpPostedFileBase> Uploads { get; set; }

…the Client-side validation no longer runs; only the server-side works. This is evident when doing a view-source. The <input> tag that gets generated is missing all the data-val attributes it needs to run. In doing a debug, GetClientValidationRules is never called.

What am I missing?

Could this be because of how I render it? I’m simply using an EditorTemplate for HttpPostedFileBase:

@model System.Web.HttpPostedFileBase
@Html.TextBoxFor(m => m, new { type = "file", size = 60 })

…and my view renders it like this:

<p>@Html.EditorFor(m => m.Uploads)</p>

Any advice is appreciated.

  • 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-06-05T09:52:08+00:00Added an answer on June 5, 2026 at 9:52 am

    Here’s what I came up with.

    I actually think the problem is ultimately caused because MVC doesn’t know that I want that Data Annotation on the List to be applied to all of its members. Nor should it I suppose.

    So I simply made a “viewmodel” wrapper around HttpPostedFileBase, and put my validator there:

    public class UploadedFile {
        [FileExtensionValidator(ErrorMessage = "Invalid Extension")]
        public HttpPostedFileBase File { get; set; }
    }
    

    Then, in my actual model, I now just use a list of those instead:

    public List<UploadedFile> Uploads { get; set; }
    

    …with no more dataannotations here of course since they’re now in UploadedFile.

    Then, with minor modifications to the view and editortemplate to use these, this now works a-ok, client side and server side. (Still, feels clunky to me. If anyone has a simpler way I’m still happy to hear it.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basic question here, can I put String variables into a position in a string
Basic question.. had to ask. Any help will be appreciated. Q: Why can't I
This might seem like a basic question and back to Http protocol 101. But
I feel like this question is basic enough to be out there somewhere, but
I decided to start a new question so it can strictly focus on the
Basic question - is it possible to access the current Page from a static
Basic question so I feel dumb but..., Whats the proper syntax below in the
Basic question! I have 2 tables PRODUCE +-----+--------------+ | id | fruit_name | +--------------------+
Really basic question I'm sure for some of you Java heads out there. I
Very basic question - but I couldn't find an answer. I have got a

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.