What is the best method for defining validation rules in Vuelidate to ensure a value matches the value of a specific field within an

Imagine having a Vue component with data structured like this:

  data: () => ({
    form: {
      old_password: {
        data: '',
        type: 'password',
        label: 'Old Password',
      },
      new_password: {
        data: '',
        type: 'password',
        label: 'New Password',
      },
      repeat_password: {
        data: '',
        type: 'password',
        label: 'New Password Confirmation',
      },
    },
  }),

The reason for this specific data format is due to utilizing the ant-design plugin for form building, leaving no room for alternative formats. The data field will hold the actual information.

Moreover, there are validation rules in place for vuelidate as follows:

  validations: {
    form: {
      old_password: {
        data: { required },
      },
      new_password: {
        data: { required },
      },
      repeat_password: {
        data: { sameAsPassword: sameAs('new_password') },
      },
    },
  },

Although the required rule functions correctly, the sameAsPassword rule seems faulty. It consistently displays an error even when using identical passwords. It appears that the comparison is not being made against the correct field. How can I adjust the rule to compare it accurately?

Answer №1

repeat_password.data is not a direct sibling of new_password. This information can be found in the official built-in validator documentation.

  • The locator can either be a sibling property name or a function. If provided as a function, it will receive the model under validation as an argument with access to all properties and methods within the component instance.

Therefore, a function must be passed into the sameAs method:

validations: {
    form: {
      old_password: {
        data: { required },
      },
      new_password: {
        data: { required },
      },
      repeat_password: {
        data: { 
          sameAsPassword: sameAs(function() {
            return this.form.new_password.data;
          }) 
        },
      },
    },
  },

Additionally, to ensure that this properly refers to the component instance inside the function, the data needed to be adjusted from an arrow function to return the correct data values:

data() {
    return {
      form: {
        old_password: {
          data: '',
          type: 'password',
          label: 'Old Password',
        },
        new_password: {
          data: '',
          type: 'password',
          label: 'New Password',
        },
        repeat_password: {
          data: '',
          type: 'password',
          label: 'New Password Confirmation',
        },
      },
    }
  },

Answer №2

First and foremost: using arrow functions for data is not recommended. It's better to define your data like this:

data() {
 return {
   form: {}
 }
}

This approach helps avoid potential context issues.

Additionally, it's uncertain if the data needs to be accessed within validations. Consider structuring your code in this manner:

export default {
  data() {
    return {
      form: {
        nestedA: '',
        nestedB: ''
      }
    }
  },
  validations: {
    form: {
      nestedA: {
        required
      },
      nestedB: {
        required
      }
    }
  }
}

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

Sending Node.js array from endpoint to Javascript function

I am facing an issue with my HTML chart that is supposed to display an array from a JavaScript function called 'window.testDataArray'. Instead of using a sample array, I want to fetch the array data from a server endpoint. However, I am unsure ab ...

JavaScript formula for calculating dates together

I'm currently developing a PHP program for generating invoices. I'm implementing a datetimepicker to select the invoice generation date and due date. Now, I need the due date field to be automatically populated by adding a specific value to the i ...

Exploring the Contrast between Using @import for Styles and js Import for Webpack Configuration

While delving into the source code of ant-design, I couldn't help but notice that each component has both an index.ts and a index.less file in the style folder. This got me thinking - why is JavaScript being used to manage dependencies here? What woul ...

Adding HTML created by PHP to a document fragment

I am trying to add a large amount of HTML generated by PHP (5000 div elements) to a document fragment and then append it to the body of the page. Here is an example of the HTML: <div itemscope itemtype="http://schema.org/Article"> <link itemprop ...

What is the method to specify a .map list within a React component that contains no elements?

I am facing an issue with updating two lists dynamically. When clicked, the item in the array should move to either the 'archived' list or the 'favourite' list. I have mapped each list which is stored in a parent component's state, ...

What strategies can I implement to safeguard against harmful Vuex mutations?

My Vue SPA quiz app utilizes a Vuex store to keep track of the number of correctly answered questions by users. This data is then transferred from the store to my server for storage in the database. However, I am concerned about the security risks. Is it ...

Is it normal for e.target.result to only work after two or three tries?

Attempting to resize an image on the client side before sending it to the server has been challenging for me. Sometimes, the image does not align correctly with the canvas used for resizing. I have noticed that I need to send the resized image at least tw ...

Enhancing jQuery functionality: Ensuring newly added elements are aware of existing functions

I need assistance with my HTML table. Each row (tr) contains a value, for example 200$, and a delete button. How can I ensure that each new row added automatically knows the recent functions without having to call them every time? $(function () { $(&ap ...

AngularJS - Utilizing Google's Place Autocomplete API Key

Recently, I started digging into Google's APIs and attempting to integrate the Places Autocomplete API with Angular. Although I'm fairly new to autocomplete features in general, I haven't included the jQuery library in my project yet. I&apos ...

JavaScript - Modify the proposed content prior to inserting it into the input field

In my current project, I have implemented a feature using jQuery UI - v1.11.4, where an HTML textbox utilizes a JavaScript autocomplete functionality. The suggested string for the textbox is created by concatenating several columns (patient_no, patient_nam ...

Increasing the values of id attributes in AngularJS

Here is an example of some HTML code: <tr ng-repeat="x in y"> <td> <div ng-attr-id="{{getId()}}"></div> </td> <td> <div ng-attr-id="{{getId()}}"></div> </td> <t ...

Initiate a click on a radio button while also retaining the selected option when the page is

This is a unique question. In my scenario, there are two radio buttons: "radio1" and "radio2." I have successfully implemented the following actions individually: Automatically triggering a click on "radio1" upon page load. This ensures that the button ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...

Is there a way to serve an HTML file using the response object in expressjs while also incorporating an external JavaScript file?

My express application successfully serves an HTML page from my disk when I initially make a GET request to "http://localhost:3000/" in the browser. Now, I am trying to access a JavaScript file that is located in the same directory on the disk as the HTML ...

How to maintain the focus within a jQuery dialog box

Exploring the world of jQuery dialog, I'm eager to incorporate it into my latest side project. My goal is to enhance accessibility by adding tabindex to the divs within the dialog for easy tab navigation. However, I encountered an issue where the focu ...

The issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

Troubleshooting: Issue with running npm start | React app not loading

npm start command seems to be stuck at this particular point - https://i.sstatic.net/5NUVF.png The application is failing to load because of this issue. Here is the content of package.json file - { "name": "reacttest", "vers ...

Encounter an issue with the Kendo editor React wrapper showcasing an error

Looking to incorporate an editor using Kendo UI, but encountering an error TypeError: list is undefined in node_modules/@progress/kendo-ui/js/editor/plugins/inlineformat.js:422 The library was installed through: npm install --save @progress/kendo-editor- ...

Encountering a problem with the scope of child_process in Node

When utilizing the child_process module in Node.js with the fork method, I am able to send data to a specific file and receive a response. However, I am not logging this data to the console after receiving it from the execution process. The code in first. ...