Last active
December 14, 2018 17:35
-
-
Save amhinson/75a8bdece96f9a33b2d826b04bd3df4f to your computer and use it in GitHub Desktop.
Yup - valid image url/source
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
yup.object().shape({ | |
imageUrl: yup | |
.string() | |
.test('valid-image-url', 'Must use valid image URL', value => | |
testImage(value, 1000).then(status => status === 'success') | |
) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const testImage = (url: string, timeout?: number) => | |
new Promise(res => { | |
timeout = timeout || 5000; | |
let timedOut = false; | |
let timer; | |
const img = new Image(); | |
img.onerror = img.onabort = function() { | |
if (!timedOut) { | |
clearTimeout(timer); | |
res('error'); | |
} | |
}; | |
img.onload = function() { | |
if (!timedOut) { | |
clearTimeout(timer); | |
res('success'); | |
} | |
}; | |
img.src = url; | |
timer = setTimeout(function() { | |
timedOut = true; | |
// reset .src to invalid URL so it stops previous | |
// loading, but doesn't trigger new load | |
img.src = '//!!!!/test.jpg'; | |
res('timeout'); | |
}, timeout); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment