views:

85

answers:

2

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?

+3  A: 

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.

SLaks
are those guaranteed to fire in a timely manner (in every major browser)? Will I have to do some timeout logic for myself?
Paul Tarjan
@Paul: It should work fine; try it.
SLaks
A: 

Do this. In this example, it will replace any non-image with a default image

<img src="xx" onerror="this.src = '/images/default.png'>
ming yeow