Javascript Image Url Verify

JavascriptImageFunctionUrlVerify

Javascript Problem Overview


I need to verify an image url to check whether the url is an image of any of these extensions:- jpeg, jpg, gif, png. Example:- when we verify this url http://www.example.com/asdf.jpg it should give us true value and with url like this http://www.example.com/asdf.php should return false. How can we do this in javascript and also i want to check the content type of url. So that we can say whether the url is an image or not.

Javascript Solutions


Solution 1 - Javascript

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 = "//!!!!/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 = "//!!!!/test.jpg";
            reject("timeout");
        }, timeout);
        img.src = url;
    });
}

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

Solution 2 - Javascript

use the HEAD http request method to check the contenttype...

$.ajax({
  type: "HEAD",
  url : "urlValue",
  success: function(message,text,response){
     if(response.getResponseHeader('Content-Type').indexOf("image")!=-1){
           alert("image");
    }
  } 
});

to check whether the string contains that extenstions you can use the inArray method,

function checkUrl(url){
   var arr = [ "jpeg", "jpg", "gif", "png" ];
   var ext = url.substring(url.lastIndexOf(".")+1);
   if($.inArray(ext,arr)){
     alert("valid url");
     return true;
  }
}

edit: updated typo

Solution 3 - Javascript

For validating image url string with regex, it's simple.

url.match(/^https?:\/\/.+\/.+$/)

All we're checking is that the url has a protocol https://, hostname foobar.com, slash / and then image name. No need to check image extension (png, jpg ...) because it is not required and browsers check image type by it's headers.

To check if image exist, attach its url to an Image constructor and check if it errors or not.

const doesImageExist = (url) =>
  new Promise((resolve) => {
    const img = new Image();

    img.src = url;
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
  });

Solution 4 - Javascript

let url = "folder/myImage.png";
if ( isValidImageURL(url) ){
    // do something if url is valid image url.
}

function isValidImageURL(str){
    if ( typeof str !== 'string' ) return false;
    return !!str.match(/\w+\.(jpg|jpeg|gif|png|tiff|bmp)$/gi);
}

Solution 5 - Javascript

A more flexible solution, suporting query params after file extension:

function isImgLink(url) {
    if(typeof url !== 'string') return false;
    return(url.match(/^http[^\?]*.(jpg|jpeg|gif|png|tiff|bmp)(\?(.*))?$/gmi) != null);
}

console.log(isImgLink('https://example.com/img.jpg')); // true
console.log(isImgLink('https://example.com/any-route?param=not-img-file.jpg')); // false
console.log(isImgLink('https://example.com/img.jpg?param=123')); // true

Solution 6 - Javascript

If you want to check that the string starts with http you can use

url.match(/^http.*\.(jpeg|jpg|gif|png)$/) != null

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn PrestonView Question on Stackoverflow
Solution 1 - Javascriptjfriend00View Answer on Stackoverflow
Solution 2 - JavascriptredDevilView Answer on Stackoverflow
Solution 3 - JavascriptCaleb TaylorView Answer on Stackoverflow
Solution 4 - JavascriptWaqas TariqView Answer on Stackoverflow
Solution 5 - JavascriptMaikon MatheusView Answer on Stackoverflow
Solution 6 - JavascriptDiego PovedaView Answer on Stackoverflow