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

后端 未结 2 1984
无人共我
无人共我 2021-01-05 19:49

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 a

相关标签:
2条回答
  • 2021-01-05 20:13

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

    <img src="xx" onerror="this.src = '/images/default.png'">
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题