Skip to content

Instantly share code, notes, and snippets.

View ekrem-aktas's full-sized avatar

Ekrem ekrem-aktas

View GitHub Profile
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 }
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" };
}
// Returns a function which runs given checkFn against a value.
const createRule = (checkFn, errorMessage) => {
return async (value) => await Promise.resolve(checkFn(value)) ? null : errorMessage;
}
// Returns a function which accepts a value to validate and runs all passed rules.
const defineValidator = (...rules) => {
return async (value) => {
for (const rule of rules) {
const errorMessage = await rule(value);