Form validation

When a user enters a form with invalid inputs, such as an invalid email address, then we want our UI to tell the user what went wrong.

We can pass invalid information to the frontend by using return someValue instead of throw Abort().

// SignUpForm.telefunc.js
// Environment: Node.js

import { shield } from 'telefunc'
const t = shield.type

shield(onFormSubmit, [t.string, t.string])
export async function onFormSubmit(email, password) {
  // Form validation
  const invalidInputs = {}

  if (!email) {
    invalidInputs.email = 'Please enter your email.'
  } else if (!email.includes('@')) {
    invalidInputs.email = 'Invalid email; make sure to enter a valid email.'
  }

  if (!password) {
    invalidInputs.password = 'Please enter a password.'
  } else if (password.length < 8) {
    invalidInputs.password = 'Password is too short: it should have at least 8 charachters.'
  }

  if (Object.keys(invalidInputs).length > 0) {
    // Instead of `throw Abort()`
    return { invalidInputs }
  }

  // Some ORM/SQL query
  const user = new User({ email, password })
  await user.save()

  return { user }
}

We could also use throw Abort({ invalidInputs }) but return { invalidInputs } is usually more convenient for form validation.