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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With