Is there a way to implement field validation in a Vue wizard form?

Trying to implement form validation using Joi in a Vue wizard form, but not sure how to set it up correctly. The objective is to control the fields before progressing to the next and final page using the next() method. I want to keep the simplicity of this wizard form without switching to VueFormWizard. I have removed unnecessary fields from the code.

<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>

Answer №1

Utilize browser validation by setting up your form like this:

<form @submit.prevent="submitMyForm">
    <input v-model="form.title" required minlength="4" maxlength="20" />

    <button type="submit">Submit</button>
</form>

With this setup, the browser will prevent form submission if the title field is empty, or if its length is below 4 or above 20 characters.

This method can handle various validations, including regex checks as well:

https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Validating_against_a_regular_expression

However, these built-in checks are limited and may not be supported by older browsers. For more specific validation needs, consider using a custom solution outlined here: https://v2.vuejs.org/v2/cookbook/form-validation.html.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Removing multiple tables simultaneously and encountering an error while utilizing ajax response text

I am facing a couple of challenges. First Issue: I encountered a problem while trying to delete groups from two tables in the database (gmembers and groups). My goal was to check if a user left a group, and if there are no remaining members in that g ...

Challenges with Organizing Data and Maintaining Database Integrity

I have been working on making this sortable code function properly. Initially, I had it working fine with <li> elements as shown in the UI examples. However, now I am trying to implement it with <div> elements. While it shouldn't be much o ...

Incorporating multiple markers into Google Maps with the help of a JSON file

I am struggling to display markers on a map for 20 restaurants from a JSON file. It seems like I may not be retrieving the data correctly. Any help or guidance in the right direction would be greatly appreciated. My current code is as follows: var map; ...

Issue with Material-ui Autocomplete: onChange event not firing when value is updated in onHighlightChange

I have been customizing Material UI's Autocomplete by adding a feature that allows users to move options to the input using keyboard events (Arrow keys up and down). Then, the user should be able to select an option by pressing the ENTER key. I am fa ...

Adding query parameters dynamically in Vue without refreshing the component

I'm attempting to update the Query Parameters in Vue without refreshing the component using Vue-Router. However, when I use the code below, it forces a component reload: this.$router.replace({query: this.filters}); Is there a way to prevent the comp ...

How do I go about updating my code for welcome messages from discord.js v12 to v13?

While watching a YouTube tutorial on welcome messages, I decided to copy the entire code. However, when I tried using this code with discord.js v13, it didn't work. Strangely enough, everything seemed to function perfectly fine with discord.js v12. In ...

Passing the value in a td element to a JavaScript function using Thymeleaf onClick

Trying to utilize "Thymeleaf" for the first time, I am attempting to pass a value to JavaScript with the following code: onclick="getPropId('${properties.id}')" The corresponding function is as follows: getPropId(inputID){alert(inputId);} Unf ...

The combination of Grunt and Babel runs smoothly, but fails to produce any results

I'm fairly new to the world of grunt and npm. After diving into the documentation, I managed to create my own package.json and a Gruntfile.js. This is how my directory structure looks: / |- src |- myfile.es6 |- anotherfile.es6 |- etc. |- ...

Swapping React components within a list: How to easily change classes

For my latest project, I am building a straightforward ecommerce website. One of the key features on the product page is the ability for users to select different attributes such as sizes and colors. These options are represented by clickable divs that pul ...

Trouble with executing two asynchronous AJAX calls simultaneously in ASP.NET using jQuery

When developing a web application in asp.net, I encountered an issue with using jQuery Ajax for some pages. The problem arose when making two asynchronous Ajax calls - instead of receiving the results one by one, they both appeared simultaneously after the ...

Ensure AngularJS ng-show and ng-hide are more secure

When using AngularJS, my goal is to conceal an element so that only authenticated users can access it. Although the ng-hide directive works, there is a vulnerability where someone could modify the class assigned to the element (ng-hide) using Developer To ...

How can I retrieve the offset top of a td element in relation to its parent tr element?

Here is some sample dummy HTML code: <table> <body> <tr> <td id="cell" style="height: 1000px; width: 200px;"></td> </tr> </body> </table> I am looking to attach a click event ...

Utilizing various Material UI Sliders on a single page with shared color properties

After creating a component called "SliderBox", I noticed that it returns a div containing a Material UI Slider with createMuiTheme and an input component. The "SliderBox" component utilizes an onHover method on the parent div to change the component' ...

Developing a standalone Vue component within an expansive project

I am currently working on a PHP project that utilizes Kirby CMS and Gulp for asset building. The challenge I am facing now is incorporating a complex calculator on the homepage using Vue, without introducing excessive new tools into my workflow. What I rea ...

Reactjs Router.push function does not behave as intended

I'm currently working with Reactjs and Next.js. I am experiencing an issue where the correct data is only displayed after refreshing the page instead of upon clicking, as intended. To solve this problem, I have attempted to use "router.push", but unfo ...

Retrieving all the information stored in the tables

I'm struggling with retrieving the content of my table cells. Some cells contain a hyphen (-) and if they do, I want to center the text. I'm facing difficulties with my jQuery code, particularly the if statement which always evaluates to false. ...

mention a numerical value/heading within a JSON list

I encountered an issue while searching through a JSON array filled with Google fonts. The fonts are structured by family -> files -> filename. However, I noticed that sometimes the filename is saved as a number. For example (refer to the bottom of th ...

Various Plus/Minus Containers

One issue I am facing is that when using multiple counters on the same page, my - and + buttons to decrease or increase the number in a text box do not function properly. The script provided below works for one counter. How can I modify this code so that ...

Declare a state in React based on certain conditions

Is it possible to conditionally set up a state based on a certain prop being provided? Consider the following scenario: function Component({scroll, children}) { const [scrollY, setScrollY] = useState(0); useEffect(() => { if (scroll) { ...

Unlocking $refs with the Composition API in Vue3 - A step-by-step guide

I am currently exploring how to access $refs in Vue 3 using the Composition API. In my template, I have two child components and I specifically need to obtain a reference to one of them: <template> <comp-foo /> <comp-bar ref="ta ...