Search code examples
javascriptvue.jsvuejs3vuetify.jstextfield

Rule of v-textfield cannot find an element declared in data


I'm using Vue3 and Vuetify and, while making the rule for the v-textfield of the confirm password field, I got this error:

I tried to compare the values of the password field and the one of the confirm password field, both associeted to the v-textfield with the v-model, but in the confirm password rule the variable of the password results undefined.
Here's the source.

Data whit rules and variables:

data: () => ({
  // Credentials
  username: '',
  password: '',
  confirmPassword: '',

  passwordRules: [
    (value) => {
      if (value?.trim().length > 0) return true
      else return 'Password is required.'
    },
  ],
  confirmPasswordRules: [
    (value) => {
      if (value?.trim().length > 0) {
        // TODO: ERROR (this.password is undefined)
        if(value === this.password) {
          return true
        }
        else return 'Passwords do not match.'
      }
      else return 'Confirm password is required.'
    },
  ],
}),

The error appears all the times that I write a character in the v-textfield, since it's in the rule:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'password')
    at confirmPasswordRules

Thanks!


Solution

  • OP was writing his data key as

    data: () => ({
    

    which is not the proper syntax for the usual

    data() {
    

    It indeed doesn't have the same meaning when it comes down to the usage of this.