Skip to content

Instantly share code, notes, and snippets.

@ekrem-aktas
Last active January 7, 2021 08:27
Show Gist options
  • Save ekrem-aktas/64fd488c1d6cb3f05401777cb7e4ca0e to your computer and use it in GitHub Desktop.
Save ekrem-aktas/64fd488c1d6cb3f05401777cb7e4ca0e to your computer and use it in GitHub Desktop.
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