Skip to content

Instantly share code, notes, and snippets.

@amhinson
Last active December 14, 2018 17:35
Show Gist options
  • Save amhinson/75a8bdece96f9a33b2d826b04bd3df4f to your computer and use it in GitHub Desktop.
Save amhinson/75a8bdece96f9a33b2d826b04bd3df4f to your computer and use it in GitHub Desktop.
Yup - valid image url/source
yup.object().shape({
imageUrl: yup
.string()
.test('valid-image-url', 'Must use valid image URL', value =>
testImage(value, 1000).then(status => status === 'success')
)
})
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