Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a URL is a valid image (in javascript)?

When submitting a form, I want to make sure a field is a valid image URL.

I could make an AJAX endpoint on my server which CURLs the URL and parses the output with an image library, but that feels a bit of overkill.

Could I get away with making an <img> element then synchronously check the response somehow?

like image 361
Paul Tarjan Avatar asked Sep 19 '10 02:09

Paul Tarjan


People also ask

How check if an image link is valid JavaScript?

To check if a url is an image, call the test() method on a regular expression that matches an image extension at the end of a string, e.g. . png or . jpg . The test() method will check if the url ends with an image extension and will return true if it does.

How do you check if it is a valid URL in JavaScript?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.


1 Answers

You can make an <img> element and handle its onerror and onload events.

If the load event fires, it's a valid image; if the error event fires, it isn't.
This even works across domains.

like image 118
SLaks Avatar answered Oct 27 '22 09:10

SLaks