Skip to content

Instantly share code, notes, and snippets.

@ekrem-aktas
Created October 6, 2020 20:20
Show Gist options
  • Save ekrem-aktas/434fe34e9b1409524fb6cd954a83b7aa to your computer and use it in GitHub Desktop.
Save ekrem-aktas/434fe34e9b1409524fb6cd954a83b7aa to your computer and use it in GitHub Desktop.
async function validateUsername(username) {
const errorNode = document.getElementById("error-text");
// Check if username is a non-empty string
if (typeof username !== "string" || username.trim() === "") {
errorNode.innerText = "Username is required";
return false;
}
// Check if username format is valid
if (!username.match(/^\w+$/)) {
errorNode.innerText = "Username must consist of characters and numbers";
return false;
}
// Check if username is unique.
const response = await fetch(`/api/checkusername/${username}`); // returns { available: true | false }
const { available } = await response.json();
if (!available) {
errorNode.innerText = `Username is already taken`;
return false;
}
return true;
}
// Call the function
validateUsername("test").then((valid) => {
// continue with registration if valid
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment