Last active
January 7, 2021 08:26
-
-
Save ekrem-aktas/2d468435831bc930d6d545010195b17e to your computer and use it in GitHub Desktop.
This file contains 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
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