How can I use field validation in my Vue wizard form?

In an example of a Vue wizard form I tried to add form validation with Joi. How do I set this up logically? The goal is to controll the fields before moving to the second and last page with the next() method. Because of the simplicity of this wizard form, I don't want to change to VueFormWizard. To increase the code I erased a lot of fields etc..

<template>
  <div>
    <div v-if="errorMessage" class="alert alert-danger" role="alert">
      {{errorMessage}}
    </div>
    <form>
      <div v-if="step ===1 ">
        <div class="form-group">
          <label for="title">Title</label>
          <input v-model="example.title"
                 type="text"
                 class="form-control"
                 id="title" />
         </div>
      <button @click.prevent="next()">Next step</button>
      </div>
      <div v-if="step === 2">
        <div class="form-group">
          <label for="userName">Email.</label>
          <input v-model="example.userName"
                 type="email"
                 class="form-control"
                 id="userName" />         
         </div>       
        <button @click.prevent="prev()">Go back</button>
        <button @click.prevent="createExample" type="submit" class="btn btn-primary">Submit</button>
      </div>
    </form>
  </div>
</template>

<script>
import Joi from 'joi'

const schema = Joi.object().keys({
  title: Joi.string().alphanum().min(2).max(40).required(),  
  userName: Joi.string().email(),
  })

export default {
  data: () => ({
    step: 1,
    errorMessage: false,
    example: {
      title: '',
      userName: ''
    }
  }),
  watch: {
    example: {
      handler () {
        this.errorMessage = ''
      },
      deep: true
    }
  },
  methods: {
    prev () {
      this.step--
    },
    next () {
      this.step++
      if (this.validUser()) {
           return false
      }
    },
    createExample () {
     // Post request
    },
    validUser () {
      const result = Joi.validate(this.huismap, schema)     
		return true
	if (result.error.message.includes('title')) {
    this.errorMessage = 'Vul een titel in van min 2 karakters'
    return false
    }
  }
}
</script>

1 answer