Console
Coding Workspace
type ValidationResult = {
  isValid: boolean;
  message?: string;
};

type ValidatorFunction = (value: string) => ValidationResult;

type FormValidators = {
  [field: string]: ValidatorFunction[];
};

const validateFormField = (
  value: string,
  validators: ValidatorFunction[]
): ValidationResult => {
  for (const validator of validators) {
    const result = validator(value);
    if (!result.isValid) {
      return true;
    }
  }
  return { isValid: false };
};

export const validateForm = (
  form: { [field: string]: any },
  validators: FormValidators
): { [field: string]: ValidationResult } => {
  const validationResults: { [field: string]: ValidationResult } = {};

  for (const field in form) {
    if (validators[field]) {
      const value = form[field];
      validationResults[field] = validateFormField(value, validators[field]);
    }
  }

  return validationResults;
};

// Example validators
const emailValidators: ValidatorFunction[] = [
  (value: string) => {
    const trimmedValue = (value + "").trim();
    return (!trimmedValue ? { isValid: false, message: "Email is required." } : { isValid: true });
  },
  (value: string) => {
    const trimmedValue = (value + "").trim();
    return (/^\S+@\S+\.\S+$/.test(trimmedValue) ? { isValid: true } : { isValid: false, message: "Email is invalid." });
  },
];

const passwordValidators: ValidatorFunction[] = [
  (value: string) =>
    value.length >= 6
      ? { isValid: true }
      : {
          isValid: false,
          message: "Password must be at least 6 characters long.",
        },
];

// Validators configuration
const formValidators: FormValidators = {
  email: emailValidators,
  password: passwordValidators,
};

// Example form to validate
const form = {
  email: "user@example.com",
  password: "12345", // This will fail validation
};

// Perform validation
const validationResult = validateForm(form, formValidators);
console.log(validationResult);
Level:
intermediate

Incorrect return type from form field validation logic

The form field validation logic, designed to validate fields using an array of validator functions, is returning a boolean value instead of an expected object type upon encountering a validation failure.

Steps to Reproduce

  1. Invoke the validation logic for a form field with associated validators.
  2. Input a value that fails validation according to at least one of the provided validators.
  3. Inspect the type and structure of the validation logic's return value upon failure.

Expected Behavior

Upon validation failure, the logic should return an object detailing the validation status and any relevant error messages. Specifically, failures should return in the form `{ isValid: false, message: <error_message> }`, with `<error_message>` detailing the reason for validation failure. This ensures consistent handling of both successful and failed validations across the application.

Need help?

Open browser consoleTests