2

HTML:

<input type="file" name="group_documents_file" id="group_documents_file" class="group-documents-file" /> 

Rule: The file to upload must have an extension JPEG, GIF or PNG, otherwise an alert must be displayed.

0

4 Answers 4

1

You simply need to pull the value of the element:

var fileName = $('#group_document_file').val(); var extension = fileName.slice('.')[fileName.slice('.').length - 1].toLowerCase(); if(extension == 'jpeg' || extension == 'gif' || extension == 'png') // Show Validated Image else alert('Choose a supported image format'); 
Sign up to request clarification or add additional context in comments.

6 Comments

No need to double slice when you can use regEx. See my answer.
If you have a problem and decide to solve it with regular expressions, now you have two problems. =D
It's an old programmer's saying, not a slight; first because you need to construct a regex that will actually solve your problem, and then second because the readability of your code is lessened when you have to mentally parse the regex to figure out what the code is doing.
Again, in my HUMBLE opinion, it really depends on the situation. When coming up with a crazy complex RegEx to a simple problem, you're right. But in this particular situation, the regex is the cleaner AND more legible one of the two.
At least use "pop" instead of "length - 1". See my answer.
|
1

See here: get the filename of a fileupload in a document through javascript on how to get the filename:

var extension = $('#group_documents_file').val().match(/[^.]+$/).pop().toLowerCase(); 

This should get you anything after the period in the filename.

EDIT:

If you don't want to use a regEx, I would recommend using split, with pop:

var extension = $('#group_documents_file').val().split('.').pop().toLowerCase(); 

Then, to check for allowed extensions, do the following:

if ( ~$.inArray(extension, ['jpg', 'jpeg', 'gif', 'png']) ) { // correct file type... } else { // incorrect file type... } 

1 Comment

Hi Joseph, the first solution doesn't work, you need to add .pop() after regEx :) var extension = $('#group_documents_file').val().match(/[^.]+$/).pop().toLowerCase();
0

The following gets the extension of the file:

JS:

$('#group_documents_file').change(function(){ var value = this.value; val = value.split("\\"); var file = (val[val.length - 1]).split('.'); var ext = file[file.length - 1]; alert(ext); }) 

Fiddle: http://jsfiddle.net/maniator/gveqX/

Comments

0

Try this

var fName = $('#group_document_file').val(); var validExtns ["jpg", "gif", "png"]; var extn = fName.slice('.')[fName.slice('.').length - 1]; if($.inArray(extn.toLowerCase(), validExtns) != -1){ // Show Validated Image } else{ alert('Invalid image format'); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.