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.ts
// Environment: Server

export async function onFormSubmit(email: string, password: string) {
  // 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 must have at least 8 charachters.'
  }

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

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

  return { user }
}