5

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?

1
  • I'm sure this is a dupe... let me see if I can dig it up... Commented Sep 19, 2010 at 2:07

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

3 Comments

are those guaranteed to fire in a timely manner (in every major browser)? Will I have to do some timeout logic for myself?
I couldn't get the onerror or on onload events to fire an img tag. According to w3schools these are not supported events. w3schools.com/tags/tag_img.asp
Very nice and simple answer
5

Do this, the following code will replace any non-image with a default image.

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

1 Comment

This works well - one slight grammar mistake - you are missing a double quote - that I will edit for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.