Javascript Image Url Verify

You can use a regular expression like this to check the file extension:

function checkURL(url) {
    return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}

This checks to see if the url ends in any of those four extensions.

I know of no way from javascript in the client to verify the content-type of a URL that isn’t on the same domain as the web page because you can’t use ajax outside of the domain of the web page. As best I know, you’d have to ship the URL to a server process and have it download the image, get the content type and return that to you.

But, you can check to see if an image tag can load the URL by using a function like this:

function testImage(url, callback, timeout) {
    timeout = timeout || 5000;
    var timedOut = false, timer;
    var img = new Image();
    img.onerror = img.onabort = function() {
        if (!timedOut) {
            clearTimeout(timer);
            callback(url, "error");
        }
    };
    img.onload = function() {
        if (!timedOut) {
            clearTimeout(timer);
            callback(url, "success");
        }
    };
    img.src = url;
    timer = setTimeout(function() {
        timedOut = true;
        // reset .src to invalid URL so it stops previous
        // loading, but doesn't trigger new load
        img.src = "https://!!!!/test.jpg";
        callback(url, "timeout");
    }, timeout); 
}

This function will call your callback at some future time with two arguments: the original URL and a result (“success”, “error” or “timeout”). You can see this work on several URLs, some good and some bad, here: http://jsfiddle.net/jfriend00/qKtra/


And, since this is now the era of Promises, here’s a version that returns a promise:

function testImage(url, timeoutT) {
    return new Promise(function (resolve, reject) {
        var timeout = timeoutT || 5000;
        var timer, img = new Image();
        img.onerror = img.onabort = function () {
            clearTimeout(timer);
            reject("error");
        };
        img.onload = function () {
            clearTimeout(timer);
            resolve("success");
        };
        timer = setTimeout(function () {
            // reset .src to invalid URL so it stops previous
            // loading, but doesn't trigger new load
            img.src = "https://!!!!/test.jpg";
            reject("timeout");
        }, timeout);
        img.src = url;
    });
}

And, a jsFiddle demo: http://jsfiddle.net/jfriend00/vhtzghkd/

Leave a Comment