Skip to content

Instantly share code, notes, and snippets.

@hypeJunction
Created November 24, 2019 17:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypeJunction/81ef20612bd325ec38ccb71b2052f99d to your computer and use it in GitHub Desktop.
Save hypeJunction/81ef20612bd325ec38ccb71b2052f99d to your computer and use it in GitHub Desktop.
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, 'abc@example.com'),
validate(assertAvailableEmail, 'abc@example.com')
]).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