Jose
Jose

Reputation: 1140

Javascript RegEx failing

I am trying to write a regular expression that will ONLY accept files with JPEG, JPG or PDF format. My attempt has been:

/^image|\/(jpe?g|pdf)$/i

But, as it stands, it won't accept PDF format (because of the 'image/*' portion).

Any help would be appreciated. Thank you.

Upvotes: 0

Views: 89

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

Not everything needs to be a regular expression:

function isValidMimeType(type) {
    return [
        'image/jpg',
        'image/jpeg',
        'application/pdf',
        'application/x-pdf',
        'application/x-bzpdf',
        'application/x-gzpdf'
    ].indexOf(type) > -1;
}

If you insist on using regular expressions, I recommend using multiple so that the code is still readable:

function isValidMimeType(type) {
    if (/^image\/jpe?g$/.test(type)) {
        return true;
    } else if (/^application\/(?:x-|x-bz|x-gz)?pdf$/.test(type)) {
        return true;
    }
    return false;
}

Of course, this code could be written shorter. There's no reason to though. You sacrifice readability when you condense it down to:

function isValidMimeType(type) {
    return /^(?:image\/jpe?g|application\/(?:x-(?:bz|gz)?)?pdf)$/.test(type);
}

Good luck ever adding another mime type to that.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074028

That expression doesn't make a lot of sense. You have an alternation there saying either match ^image or match /(jpe?g|pdf)$.

If you want to match image/jpg, image/jpeg, and application/pdf, then:

/^(?:image\/jpe?g|application\/pdf)$/

Note, though, that PDFs can have a few other MIME types. Perhaps:

/^(?:image\/jpe?g|application\/(?:pdf|x-pdf|x-bzpdf|x-gzpdf))$/

...would be more inclusive.

Upvotes: 4

Related Questions