Putting Vee-Validate's confirmed rule to the test

I am encountering some challenges testing a Vee-Validate confirmed function on a Vue form that is constructed using Vuetify. The component I am attempting to test has the following structure:

<template>
    <form novalidate ref="loginForm" v-model="formValid" @submit.stop.prevent="formSubmitted" @keyup.enter="formSubmitted">
      <v-container grid-list-md text-xs-center>
        <v-layout column>
          <v-flex>
            <v-text-field
              name="passwordField"
              label="Enter your Password"
              hint="At least 6 characters"
              v-model="submissionDetails.password"
              :type="passwordShown ? 'text' : 'password'"
              min="6"
              required
              :append-icon="passwordShown ? 'visibility_off': 'visibility'"
              :append-icon-cb="()=>(passwordShown = !passwordShown)"
              v-validate="'required|min:6'"
              data-vv-name="password"
              :error-messages="errors.collect('password')"
              ref="password"
              @change="inputTriggered"
              @input="inputTriggered"
            />
          </v-flex>
          <v-flex v-show="createAccountTicked">
            <v-text-field
              name="confirmPasswordField"
              label="Confirm your Password"
              hint="At least 6 characters"
              v-model="confirmPassword"
              :type="passwordShown ? 'text' : 'password'"
              min="6"
              required
              :append-icon="passwordShown ? 'visibility_off': 'visibility'"
              :append-icon-cb="()=>(passwordShown = !passwordShown)"
              v-validate="'required|confirmed:$password'"
              data-vv-name="confirmPassword"
              :error-messages="errors.collect('confirmPassword')"/>
          </v-flex>
        </v-layout>
      </v-container>
    </form>
  </template>
  <script>
  export default {
    name: 'email-password-form',
    data () {
      return {
        submissionDetails: {
          email: '',
          password: ''
        },
        confirmPassword: '',
        passwordShown: false,
        createAccountTicked: false
      };
    }
  };
</script>

The validation of error messages works as intended, showing correctly on screen and disappearing when passwords match. However, the following test fails:

 describe.only('validation', () => {
    it('should not attach an error to confirm password when it does match the password', async () => {
      const wrapper = mount(EmailPasswordForm, { localVue });
      wrapper.setData({
        submissionDetails: {
          password: 'wwwwww'
        },
        createAccountTicked: true,
        confirmPassword: 'wwwwww'
      });
      
      await wrapper.vm.$validator.validate('confirmPassword');

      console.log(wrapper.vm.errors.collect('confirmPassword'));
      
      console.log(wrapper.vm.submissionDetails.password === wrapper.vm.confirmPassword);
      
      expect(wrapper.vm.errors.has('confirmPassword')).to.be.false;

    });
  });

Even though the password and confirmPassword strings are identical, the validator still flags an error for the confirm password field. I'm seeking assistance in understanding why this issue occurs.

Answer №1

After some investigation, it appears that the unusual behavior is actually a result of Vee-Validate's method of comparing values for multi-field validation and how those values are passed along. (Refer to this discussion)

To resolve this issue, I made use of the new is validation rule, which enables me to compare values against the model rather than the field's content. By modifying the contents of the v-validate rule from 'required|confirmed:$password' to

v-validate="{required: true, is: submissionDetails.password}"
, I was able to address the problem effectively.

I'm posting this here in case anyone else encounters a similar situation.

Answer №2

For the scenario I encountered, I found success using one of these two approaches:

<input 
 v-validate="{ required : true,  confirmed: 'password'}" 
 type="password" name="confirm_password"  
 class="form-control" 
 placeholder="Confirm Password" 
 v-model="field.confirm_password" 
 data-vv-as="confirm password">

<input 
 v-validate="{ required : true,  confirmed: field.password}" 
 type="password" name="confirm_password"  
 class="form-control" 
 placeholder="Confirm Password" 
 v-model="field.confirm_password" 
 data-vv-as="confirm password">

Answer №3

After encountering a frustrating issue in Chrome where validation errors were persisting even when disabled, I found a solution. This problem arose from using both the required and confirmed:password attributes within the

v-validate="'required|confirmed:password'"
directive.

 <input
 v-validate="{ required : true,  confirmed: field.password}" 
 type="password" name="confirm_password"  
 class="form-control" 
 placeholder="Confirm Password" 
 v-model="field.confirm_password" 
 data-vv-as="confirm password">

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

The Vue.js expression is malfunctioning

I am encountering an issue with my expressions. I have successfully made a REST API call, which is functioning properly. The data is loading and being written to the console without any problems. However, I am facing difficulties when trying to display thi ...

Using VueJs, create a dynamic css class name to be applied inline

Can VueJs handle a scenario like this? Html: <div class="someStaticClass {{someDynamicClass}}">...</div> JS: var app = new Vue({ data: { someDynamicClass: 'myClassName' }, mounted: function() { ...

Understanding Vue's event handling methods can be a bit confusing at first

In my Vue application, I have a parent component that toggles between "edit" mode and read-only mode for all components. The functionality is implemented successfully using a data object. Some of the components are split out into child components. When t ...

Display and conceal various elements in Vue.js using a data list

I'm a beginner in Vue.js, currently using Vue+Webpack. I am trying to make each link display data based on their respective ids when clicked, and match with the show attribute. I have created this functionality in a .vue file. export default { el ...

Making a quick stop in Istanbul and NYC to collect a few important files

Setting up Istanbul/Nyc/Mocha for test coverage in my project has been a bit of a challenge. While I was successful in running Nyc, I noticed that not all the .ts files in my project were being picked up for test coverage. When I execute npm run coverag ...

Are the checkbox inputs automatically selected when the page loads?

Can't Figure Out Why Checkbox Inputs in My Vue App Stay Checked The data structure I'm working with is as follows: data: { students: [ { "id": 189, "first_name ...

Vue.js creates a new row in the table with an undefined array of data

Trying to create a new row when clicking "+" using Vue Js Encountering an error: tablerows is not defined Vue.component('inp-row', { props: ['data'], template: `<tr :id="data.row_id" ><td> 1</td><td>2 < ...

Discovering Geo Coordinates with Vue.js

To ensure accuracy, I am setting a 10,000 millisecond timeout to retrieve the client's current geolocation. var options = { timeout: 10000 }; This function is written in JavaScript: function getCoordinates() { return new Promise(functi ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

How can I access the Vue instance in Vuepress2 in order to utilize external Vue plugins?

Trying to implement v-wave within VuePress 2 (the updated version powered by Vue 3). Followed the documentation and attempted to integrate v-wave as a local plugin in VuePress 2. .vuepress/config.js const vwave = require('path/to/v-wave.js'); ...

What is the best way to avoid duplicating child components in conditional rendering?

Scenario I have created a custom button component using Vue: <custom-button type="link">Save</custom-button> This is the template for my custom button component: // custom-button.vue <template> <a v-if="type === &apo ...

Bottom navigation in Vuetify fails to function properly on smaller screens

Utilizing Vuetify's bottom navigation component in my web application, I have implemented multiple sections that require navigation items on the bottom navigation bar. The code snippet below showcases the component being used: <template> < ...

Order comments based on their category using vue.js

I have a component form with select filter: <template> <div class="form-group"> <select name="" v-model="filterRev" @change="filterReviews(filterRev)" class="form-control" id=""> <option ...

How to Handle an Expired Access Token in VueJS Laravel Passport?

My Vuejs SPA is connected to a Laravel API backend. After successfully obtaining the personal access token, I store it in both localStorage and Vuex state as shown below: token: localStorage.getItem('token') || '', expiresAt: localStor ...

Vue-Routes is experiencing issues due to a template within one of the routes referencing the same ID

I encountered an issue while developing a Vue application with Vue-routes. One of the routes contains a function designed to modify the background colors of two divs based on the values entered in the respective input fields. However, I am facing two probl ...

The v-data-table-server is failing to refresh the component within the table template

I am utilizing a Vuetify v-data-table-server (docs) that dynamically updates itself by fetching data from an API. <template> <v-data-table-server v-if="events.length > 0" v-model:items-per-page="events_limit" : ...

What is the best way to retrieve the updated input value in Vue?

I am working with a dates object that gets passed to a component, and I need to update the list when a new date is clicked. I believe using a computed property to set the date is the way to go. I initially tried using data, but the value wouldn't chan ...

Seeking a method to display a tooltip exclusively when the element is cut off

Can someone assist me with finding a solution to display the tooltip element only when the span element is truncated? <q-td v-for="(col,index) in props.cols" :key="col.name" :props="props"> <span class="t ...

Experiencing challenges during the creation of a NUXT build

Trying to build a Nuxt SSR app, but encountering an error related to the css-loader during the build command execution. The issue seems to be with Invalid options object. ERROR in ./node_modules/vue2-google-maps/dist/components/streetViewPanorama.vue (./no ...

Ways to ensure your component is updated when there are changes to the props in N

I need to update the data every time there is a change in props within the component, and I want to display it without having to reload the page. pages/invoice/index.vue: <template> <div> <b-table-column field="InvoiceNo" ...