最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

forms - How can I test if a URL is a valid image (in javascript)? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Sep 19, 2010 at 2:05 Paul TarjanPaul Tarjan 50.6k59 gold badges175 silver badges214 bronze badges 1
  • I'm sure this is a dupe... let me see if I can dig it up... – Yi Jiang Commented Sep 19, 2010 at 2:07
Add a comment  | 

2 Answers 2

Reset to default 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.

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

<img src="xx" onerror="this.src = '/images/default.png'">
发布评论

评论列表(0)

  1. 暂无评论