LearnFrenzy
Sign in Take a free test

Callbacks · Callbacks Coding Problems · Question 5

Validation with success and failure callbacks in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
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
main.js
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);

Output Verified by running it on Node.js

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links