Skip to content

Server-side Validation Errors

The submitHandler() in the code source shows how you could handle validation errors from the server

Sample code for handling errors from the server

js
const submitHandler = async function (formData, formController) {
  try {
    const response = await fetch('https://api.example.com/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData)
    })

    // the status code returned by the server 
    // when there are validation errors
    if (response.status === 422) {
      const errorData = await response.json()

      if (errorData.errors) {
        //---------------------------------------
        // this is where the magic happens
        // you have access to the formController
        //---------------------------------------
        formController.setErrors(errorData.errors)
        alert('Validation failed. Fix the errors and try again')
      } else {
        alert('Validation failed, but no error details provided.')
      }
      return
    }

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    alert('Data submitted successfully!')
  } catch (error) {
    alert(`An error occurred: ${error.message}`)
  }
}

Source code

vue
<template>
  <Enforma
    ref="formRef"
    :data="data"
    :validator="validator"
    :submit-handler="submitHandler"
  >
    <div class="grid grid-cols-2 gap-4 mb-4">
      <EnformaField
        class="col-start-1 col-end-3"
        name="name"
        required
        label="Name"
        help="Only John Wick can submit this form"
        :input-props="{class: 'w-full'}"
      />
      <EnformaField
        class="col-start-1 col-end-3"
        name="email"
        required
        label="Email"
        :input-props="{class: 'w-full'}"
      />
    </div>
  </Enforma>
</template>

<script setup>
import { Enforma, EnformaField } from '@'
import { createEncolaValidator } from '../../../src/validators/encolaValidator'

const data = {
  name: null,
  email: 'johnwick@gmail.com'
}

const rules = {
  name: 'required',
  email: 'required|email',
}

const validator = createEncolaValidator(rules)

// The submit handler simulates talking to the server and returning errors
const submitHandler = (formData, formController) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (formData.name !== 'John Wick') {
        formController.setErrors({
          name: ['You are not allowed in this establishment']
        })
        reject(false)
        return
      }
      alert('Data sent to server: ' + JSON.stringify(formData))
      resolve(true)
    }, 1000)
  })
}
</script>

Released under the MIT License