Skip to content

Form Validator

Mixin used to validate forms. It provides a set of validators and a way to handle server errors.

Usage

Here is an example of a form that uses the mixin:

vue
<template>
  <v-form ref="form">  
    <v-text-field
      v-model="model.string"
      :error-messages="serverErrors.string"
      :rules="rules.string"
    />
  </v-form>
</template>

<script>

import { mergeDefaults, formValidatorMixin } from '@we/nuxt/forms'

const defaultValues = {
  string: '',
  number: 0,
}

export default {
  mixins: [formValidatorMixin],
  props: {
    value: {
      type: Object,
      required: false,
      default: undefined
    },
  },
  data: () => ({
    model: null,
  }),
  computed: {
    rules () {
      return {
        string: [this.validatorRequired],
        number: [],
      }
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (val) {
        this.resetValidation()
        this.model = mergeDefaults(val, defaultValues)
      }
    }
  },
  methods: {
    resetValidation () {
      this.clearServerErrors()
      this.$refs.form?.resetValidation()
    },
    reset () {
      this.model = mergeDefaults({}, defaultValues)
      this.resetValidation()
    },
    async save () {
      if (!this.$refs.form.validate()) { return }

      try {
        const data = { ...this.model }
        const res = await this.$api.$post(`resource`, data)
        this.$emit('input', res)
      } catch (e) {
        this.checkServerErrors(e)
        // you can handle errors that are not 422
        this.$emit('error', e)
      }
    }
  }
}
</script>

Validators

validatorRequired

Check if val is truthy !!val

validatorRequiredArray

Check if val is an Array Array.isArray(val)

validatorNotNull

Check if val is not null val !== null

validatorMin(length)

Check if val is at least length characters long val.length >= length

validatorMax(length)

Check if val is at most length characters long val.length <= length

validatorMaxFileSize(bytes)

Check if val is at most bytes bytes long val.size <= bytes

validatorRequiredNumber

Check if val is a number !isNaN(val)

validatorEmail

Check if val is a valid email address

validatorPhone

Check if val is a valid phone number

validatorEquals(match, message)

Check if val is equal to match val === match if not return message

Server Errors

This mixin will automatically handle server errors and set them in the serverErrors object

When we do a POST or PUT request to the server and a 422 response is returned, we need to show the errors to the user.

js
try {
  const data = { ...this.model }
  const res = await this.$api.$post(`resource`, data)
} catch (e) {
  if(!this.checkServerErrors(e)) {
    // you can handle errors that are not 422
    this.$emit('error', e)
  }
}

Using the checkServerErrors method, the mixin will check if the error is a 422 error and set the errors in the serverErrors object. We can then use the serverErrors object to show the errors in the form.

vue
<v-text-field
  v-model="model.string"
  :error-messages="serverErrors.string"
/>

If some of the keys in the serverErrors object are not shown in the form they will be shown with $notify.error to avoid silent errors.

Methods

checkServerErrors(error, options)

Check if the error is a 422 error and set the errors in the serverErrors object

  • options.notifyUntracked: Boolean - Show untracked errors with $notify.error (default: true)
  • options.scroll: Boolean|String - Scroll to the first error in the form (default: .v-input.error--text)

clearServerErrors()

Clear the serverErrors object

checkUntrackedServerErrors()

Returns the errors in the serverErrors object that are not shown in the form

TIP

Untracked errors use a Proxy to detect the keys that are accessed. They keep track of it if you access them via template or by js.

Properties

serverErrors Proxy

Object with the errors returned by the server

untrackedServerErrors read-only

Object with the errors returned by the server that are not shown in the form

allServerErrors

Object with all the errors returned by the server