0

I am trying to validate image files before they are uploaded using javascript/jquery.

Here is what I have so far:

$('#cropimages').click(function(){
    i = 1 ;
    var valid = new RegExp('/^.*\.(jpg|jpeg|png|gif)$/') ;
    $('input').each(function(){

        if($(this).attr('name') == 'file'+i)
        {
            val = $(this).val() ;

            r = valid.exec(val) ;
            alert(r) ;
            i++ ;
        }
    })
    //$('#topperform').submit()
})

But it keeps coming back null no matter what kind of file I choose.

What do I need to do to my RegExp to make this work?

1
  • By the way, I would make your regular expression case insensitive var valid = /^.*\.(jpg|jpeg|png|gif)$/i; just in case your file contains extensions in uppercase like .JPG Commented Dec 21, 2012 at 12:55

1 Answer 1

6

Use a regular expression literal:

var valid = /^.*\.(jpg|jpeg|png|gif)$/;

If you really want to use the RegExp consturctor then omit the delimiters.

var valid = new RegExp('^.*\.(jpg|jpeg|png|gif)$');

Related

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

1 Comment

One tiny thing; you don't need the new keyword when instantiating a RegExp :)

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.