Created
November 24, 2019 17:34
-
-
Save hypeJunction/81ef20612bd325ec38ccb71b2052f99d to your computer and use it in GitHub Desktop.
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 assertValidEmail = (value, errorMessage) => { | |
const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; | |
if (!pattern.test(value)) { | |
throw new Error(errorMessage || translator('error.email.malformatted', { email: value})); | |
} | |
}; | |
const assertAvailableEmail = async (value) => { | |
return fetch('/validate_email', { | |
// API call details | |
}).then(async (response) => { | |
if (response.ok) { | |
return true; | |
} | |
const data = await response.json(); | |
throw new Error(translator(data.message, data.context)); | |
}); | |
}; | |
const validate = async (validator, value, errorMessage) => { | |
return new Promise(async (resolve, reject) => { | |
try { | |
await validator(value, errorMessage); | |
resolve(); | |
} catch (err) { | |
reject(err); | |
} | |
}); | |
}; | |
Promise.all([ | |
validate(assertValidEmail, '[email protected]'), | |
validate(assertAvailableEmail, '[email protected]') | |
]).then(() => { | |
// email is valid | |
}).catch((err) => { | |
alert(err.message); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment