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

Rails: Utilizing AJAX to dynamically populate Bootstrap dropdown menus

In the setup I have, there is a dropdown responsible for displaying notifications. <li class="notifications dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-remote="true" data-toggle="dropdown" data-target="#" href="/notifi ...

Ways to dynamically assign value to a checkbox using jquery

var sites = sites_str.split(","); $.each(sites,function(i,j) { $('.check').append("<input type=checkbox name=site_name value=sites[i]>"+sites[i] +"</br>" }) I am facing an issue when trying to retrieve the values of selected check ...

A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized. window.addEventListener('resize',function() { let mapwidth = $('.canvas').attr("width") l ...

populating a HTML image tag 'src' attribute with data extracted from API javascript code

Hey there! I'm currently working on integrating an image element from the openweatherAPI that corresponds to the weather icon retrieved from the JSON data when a user inputs a city. This means displaying images like scattered clouds or clear skies bas ...

Looping through JSON objects using for loop

I am trying to implement a for loop with the following json data. The console.log function is working properly, but when I use it in the javascript function, it does not work as expected. I want the for loop to be functional within the javascript function ...

Pass the $scope object from a controller to a modal controller

I am facing an issue with transferring the $scope variable from ctrlone to ctrltwo, which is a modal window on my page. When I open the modal in ctrlone, my code looks like this: var modalInstance = $modal.open({ templateUrl: 'Modal.html&ap ...

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

Creating custom events in a JavaScript constructor function

Just beginning to learn JavaScript. I have a custom function that I want to assign events to in the constructor. var myFunction = function(){ /* some code */ } myFunction.prototype.add=function(){ /* adding item*/ } Now I am looking to add an event to ...

I am unable to configure the value using NG-Options

Currently, I am facing an issue with loading a select box using the ng-options directive. The problem is that I am unable to have the options display values ranging from 23-26, instead of 0-3. The values should match the "eigenschap_id" that I pass throug ...

Flexbox helps create responsive layouts with ease

Utilizing flex to centrally position my element within my layers has worked well for me, but I encountered an issue when switching to a smaller screen size. The element simply scales down in size instead of taking up the full width like it does with Bootst ...

Is it possible to program Zapier to automatically open a hyperlink that was included in an email?

Currently, I am utilizing Mailparser for extracting information from a booking email, and then leveraging Zapier to input this booking into our system. Within the email, there exists a link that needs to be accessed in order to confirm the booking. I am i ...

Trouble with Chakra UI loading Images from local sources

I'm running into issues when trying to load local images using the Chakra UI library in combination with Next.js. <Image src="./homepage/footer/Black.svg" /> Here is the current folder structure: When checking my console, I see the f ...

Utilize the Google Maps API to align an SVG symbol with the direction of an aircraft's

I have been struggling to update the rotation of the Google Maps API SVG aircraft symbol to display the correct heading as it moves. Although it initially loads with the correct heading, I can't seem to figure out how to dynamically update it. I' ...

Guide on transferring control from a successful jQuery event to an HTML form

I am currently using the following jQuery code to validate user details. $.ajax({ type: "POST", url: "Login", data:'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass), ...

Having trouble with your computed includes not working in Vue.js? Unsure of how to fix it?

How come when I use "includes" in Vue with my v-model, Vue.js logs an error? However, if I write (.includes("blabla)), everything works fine. What could be the issue? Also, how can I return the entire array if the (if) condition will work? For example, ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

How can we capture the current row's value for later retrieval?

Using datatables to display data from a mySQL database, I am looking to extract the current row's value and present it in a modal for editing. This is how the data is integrated into Datatable: $(document).ready(function() { $(' ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

The HTTP request is malfunctioning in a different location

I'm facing an issue where my code works in the w3schools code editor, but not on localhost or cpanel host. When I try to run it on another host, it gives me a bad request and doesn't return the answer. Here is the code snippet that I am working ...