Created
October 6, 2020 20:20
-
-
Save ekrem-aktas/434fe34e9b1409524fb6cd954a83b7aa 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) { | |
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