Last active
January 7, 2021 08:27
-
-
Save ekrem-aktas/64fd488c1d6cb3f05401777cb7e4ca0e 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 validateUsername(username) { | |
if (typeof username !== "string" || username.trim() === "") { | |
return { valid: false, reason: "Username is needed" }; | |
} | |
if (!username.match(/^\w+$/)) { | |
return { valid: false, reason: "Username must consist of characters and numbers" }; | |
} | |
const response = await fetch(`/api/checkusername/${username}`); // returns { available: true | false } | |
const { available } = await response.json(); | |
if (!available) { | |
return { valid: false, reason: `Username is already taken` }; | |
} | |
return { valid: true, reason: null }; | |
} | |
function showError(text) { | |
document.getElementById("error-text").innerText = text; | |
} | |
// Use it. | |
validateUsername("test").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