0

I have a form where administrator can define file extensions that are allowed. I have given a textbox for file extensions where admin can write extensions, comma separated for multiple. Now i want to know how can i validate that user input contains all the valid extensions like doc,docx,jpg,mp3,wmv.

I am using JQuery and C# in an Asp.Net MVC application

1
  • You realize that file name conventions are just conventions, and that different client platforms may have differing conventions, right? File type checking really has to be done on the server with a content sniffer; you never really know a file is OK until you've actually examined the bytes inside it. Commented Feb 12, 2011 at 15:57

1 Answer 1

1

bind an event to your file element change event and read the filename from it to verify that it is one of your allowed types.

example:

 $("#yourFileElementId").change(function(ev){
      var filename = $(this).val();
      if(/(\.doc$)|(\.docx$)|(\.jpg$)|(\.mp3$)|(\.wmv$)/.match(filename)){
          // filename has one of the extensions
      } else {
          alert("only specified file types are allowed");
          $(this).val(""); //This should empty the file input.
      }
 }

Hope that helps!

Sign up to request clarification or add additional context in comments.

4 Comments

I think you miss understood my question. File extensions are not fixed user input file extensions in a textbox.
You need to specify when Admin is saving the allowed extension form where are you saving this settings.... Probably in a DB as configuration. You can generate and attach the JavaScript string from code behind of your ASP.Net page and create the dynamic regex check as done by ehudokai for file extension settings.
I'll not consider a -1 for this answer... adding +1 since the solution is very much adoptable in your situation.
@Fraz, Sorry I missed the part about the admin supplying the extensions somewhere. I'm not a c# guy, so I'm less familiar with its conventions. But you could pass that list of extensions to a hidden input field on your pages and then loop through it with similar code. It is best practice to double check things on the backend as well, but since I'm not a c# guy, I'm not going to be much help there. Let me know if you want me to update my example assuming you create a hidden field with a comma seperated list of extensions in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.