0

I have a file upload in my page. I defined an attribute with name: "filetype".

<input filetype=".jpg|.jpeg|.png" id="attachments" type="file">

I want when I select a file from file upload, with the javascript, I check file type:

    function onSelect(e) {
    if (!e.files[0].extension.match('/' + $("input[type='file']").attr('filetype') + '/i')) {
        alert('file type is wrong');
        e.preventDefault();
    }    
}

Now, when I select a file with .jpg format, e.files[0].extension would be

.jpg

and '/' + $("input[type='file']").attr('filetype') + '/i' is

/.jpg|.jpeg|.png/i

but e.files[0].extension.match('/' + $("input[type='file']").attr('filetype') + '/i') returns

null

and then alert fires. Why? and how I solve this problem? Thanks.

2
  • 2
    You can't build a literal regex with concatenation, use the RegExp constructor. Commented May 6, 2014 at 5:30
  • Thanks alot. That's right. I use RegExp and it solved. Please write your comment as answer, that I marked is as answer. Commented May 6, 2014 at 5:54

1 Answer 1

1

You can't build a literal regex with concatenation, you need to use the RegExp constructor.

I would suggest you do the following:

<input data-filetype="jpg|jpeg|png" id="attachments" type="file">

Then:

function onSelect(e) {
    // "this" is the file input
    // if you attach the function to an event
    // like `$('input:file').change(onSelect)`
    var filetypes = $(this).data('filetype');
    var re = RegExp('\\.('+ filetypes +')$','i');
    if (!re.test(e.files[0].extension)) {
        alert('file type is wrong');
        e.preventDefault();
    }    
}
Sign up to request clarification or add additional context in comments.

Comments

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.