Question 5
Back to Exercise
Write register(user, onSuccess, onFailure) that validates a name, an email and a password and calls exactly one of the two callbacks.
Solution
function register({ name, email, password }, onSuccess, onFailure) {
const errors = [];
if (!name?.trim()) errors.push("name is required");
if (!/^\S+@\S+\.\S+$/.test(email ?? "")) errors.push("email is invalid");
if ((password ?? "").length < 8) errors.push("password must be 8+ characters");
if (errors.length) return onFailure(errors);
onSuccess({ name: name.trim(), email });
}
const ok = (u) => console.log(`Welcome, ${u.name}!`);
const fail = (errs) => console.log("Fix:", errs.join("; "));
register({ name: "Asha", email: "asha@lf.in", password: "secret123" }, ok, fail);
register({ name: " ", email: "asha@lf", password: "123" }, ok, fail);
Welcome, Asha! Fix: name is required; email is invalid; password must be 8+ characters
All checks run first so every problem is reported together; return onFailure(…) guarantees that only one callback is called.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!