Skip to content

Instantly share code, notes, and snippets.

@ekrem-aktas
Last active January 7, 2021 08:26
Show Gist options
  • Save ekrem-aktas/2d468435831bc930d6d545010195b17e to your computer and use it in GitHub Desktop.
Save ekrem-aktas/2d468435831bc930d6d545010195b17e to your computer and use it in GitHub Desktop.
async function isUsernameAvailable(username) {
const response = await fetch(`/api/checkusername/${username}`); // returns { available: true | false }
return (await response.json()).available;
}
async function validateUsername(username, usernameUniquenessCheckFn) {
if (typeof username !== "string" || username.trim() === "") {
return { valid: false, reason: "Username is needed" };
}
if (!username.match(/^\w+$/)) {
return { valid: false, reason: "Username must contain characters and numbers" };
}
const available = await usernameUniquenessCheckFn(username);
if (!available) {
return { valid: false, reason: `Username ${username} is already taken` };
}
return { valid: true, reason: null };
};
function showError(text) {
document.getElementById("error-text").innerText = text;
}
// Use it.
validateUsername("test", isUsernameAvailable).then(({ valid, reason }) => {
if (!valid) {
showError(reason);
return;
}
// continue with registration
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment