Tips for getting Vue's element-ui validateField() function to function correctly in conjunction with v-if?

Kindly observe the password fields. The fields for 'Password' and 'Confirm Password' are displayed upon clicking on the 'Change Password?' button.

The provided code functions properly and effectively validates the form using 'v-show', however, it fails to validate when 'v-if' is utilized.

I comprehend the roles of 'v-show' and 'v-if', alongside the functionalities within 'data(){}'. This information is clearly outlined in element-ui's documentation which can be accessed via this URL:

<template lang="pug">
  el-dialog( width="600px", title="Users", :visible.sync="dialogVisible")
    el-form.demo-ruleForm(:model="editedItem", status-icon, :rules="formRules", ref="userForm", label-width="140px")
      el-form-item(label="Name", prop="firstName")
        el-input(v-model="editedItem.name", auto-complete="off")

      template(v-if="!changePassword")
        el-form-item
          el-button(@click="changePassword = true") Change Password?
      template(v-else)
        _el-form-item_(label="Password", prop="password")
          el-input(type="password", v-model="editedItem.password", auto-complete="off")
        
        _el-form-item_(label="Confirm Password", prop="confirmPassword")
          el-input(type="password", v-model="editedItem.confirmPassword", auto-complete="off")
    
    .dialog-footer(slot="footer")
      el-button(type="primary", @click="submitForm('userForm')") Save
</template>

<script>
export default {
  name: 'dialog-add-edit-user',
  props: {
    editedItem: Object,

  },
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please input the password'))
      } else {
        if (this.confirmPassword !== '') {
          this.$refs.userForm.validateField('confirmPassword')
        }
        callback()
      }
    }

    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please input the password again'))
      } else if (value !== this.editedItem.password) {
        callback(new Error("The two inputs don't match!"))
      } else {
        callback()
      }
    }

    return {
      formRules: {
        password: [
          {
            validator: validatePass,
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          {
            validator: validatePass2,
            trigger: 'blur'
          }
        ]
      },
      dialogVisible: false,
      changePassword: false,
      editedItem: {
        name: '',
        password: '',
        confirmPassword: ''
      }
    }
  },

  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit('save-item');
          console.log('Submit Successful!');
        } else {
          console.log('Error submitting the form');
          return false;
        }
      });
    }
  }
}
</script>

Answer №1

It seems like I've pinpointed the issue now.

Your validation is actually working fine, but it's only checking passwordChange, not name and password.

If you understand the functionality of `v-show` and `v-if`, you'll realize that these elements are dynamically added and removed based on conditions.

The problem arises because the element library goes through an initialization phase when these elements are added. Later on, the element can be referenced using `$refs[formName].validate`, as seen in `SubmitForm`.

When you use `v-if` or `v-else`, since the elements weren't present initially, they won't function correctly.

You have two choices: stick with `v-show`, which should be straightforward, or utilize a hack I've used with 3rd party libraries that lack manual or automatic reload capabilities. The hack involves adding a `key` attribute to the main element. Here's how your HTML would look:

<el-form
  class="demo-ruleForm"
  :model="editedItem"
  status-icon="status-icon"
  :key="'form'+changePassword"  <--- this is the magic
  :rules="formRules"
  ref="userForm"
  label-width="140px"
>

And in pug:

el-form.demo-ruleForm(:model="editedItem", :key="'form'+changePassword", status-icon, :rules="formRules", ref="userForm", label-width="140px")

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

I am hoping to create the ability to overlay boxes onto an image retrieved from the backend system

Looking for a way to accomplish this in Vue. I've obtained the offsettop value of the container where my image is displayed. My goal is to dynamically add divs of specific sizes over the image based on certain coordinates, and have them stay fixed on ...

Managing Form Data with Vuex

Within my Vuex implementation, I have two computed properties used to display state data: computed:{ dataTab:function(){ return this.$store.state.form; }, ...Vuex.mapState({ mapA: state=>state.form.a }), }, Afte ...

The jQuery AJAX function appears to be unresponsive and failing to execute

I have a form that needs to update values on click of a radio button. Unfortunately, my jQuery skills are lacking. Here's what I have tried so far: HTML: <form> <input type="radio" checked="true" id="q1r1" name="q1" value="Awesome"> ...

Error: The react.js application is unable to access the property 'classList' of a null object

I've encountered a bug that's been causing me some trouble. Every time I try to run my react application, I keep getting an error message that reads TypeError: Cannot read property 'classList' of null. As someone who is new to react, I& ...

issue with visibility of checkbox in material ui table row

In a separate file called TradesTable.js, I have created a table using Material UI for my React app. const DummyTableRow = (props) => { let myRows = props.trades.map((trade, index) => { return <TableRow> <TableRowColumn ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...

A guide on utilizing the javascript function to toggle the checkbox in each row of a gridview

I am looking to implement a function that checks checkboxes row by row based on specific conditions. The first condition requires an alert popup if three checkboxes are selected in the same row consecutively ("You can't select continuous three hou ...

Is it possible to change the background color of the scrolling page?

Let's say I have 10 different sections, each with a unique background color assigned to them. As the user scrolls down from section 1 through 10, my goal is to dynamically change the body tag's background color based on which section is currentl ...

What is the best way to set the theme for Material-UI in a React application?

I find myself puzzled when it comes to styling a front-end based on Material-UI. Can someone clarify where the theme originates from in the following example code and what impact the theme has? import React from "react"; import Container from "@material- ...

Struggling to make AngularJS routes function properly

After starting from scratch, I rebuilt it with freshly downloaded angularJS (version 1.5.8). I simply placed both angular.js and angular-route.js in the library folder following this setup: https://gyazo.com/311679bf07249109671d621bc89d2d52 Here is how in ...

What could be causing the header of the datatable to be out of alignment with the rest of

I'm facing an issue with my datatable where the header is misaligned with the content. Can someone please assist me in adjusting the header and content so that they are parallel? It doesn't look right at the moment. <div style="margin-top:1 ...

Do form validations affect the values assigned to ng-model objects?

If a form has the structure below: <form> <input type="text" required ng-model='myValue' ng-maxlength='5'></input> {{myValue}} {{myValue.length}} </form> Is there a way to prevent the model from b ...

What is the best way to eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than inde ...

Tips on identifying the method to import a module

Currently, I am including modules into my Node project like this: import * as name from "moduleName"; Instead of the old way: var name = require("moduleName"); In the past, we used require in Node projects. My question is, is there a difference in ...

What is the method for identifying which individual element is responsible for activating an event listener?

While working on a color picker project in JavaScript for practice, I encountered an issue. I needed the #screen element to display the selected color when clicked. How can I determine which color has been clicked and pass its value to the function so that ...

How to retrieve text values across various browsers using Vue.js

Whenever I type something in a text box, it displays the text value based on its ID. This code works perfectly when running it on my laptop at http://localhost:8080/. If I open the same website on my phone at http://xxx.xxx.x.xxx:8080/, it shows the same ...

Looking for a way to extract information from two nested objects within an array by utilizing lodash, and then transferring it as a property to a react component

My react components require dynamic preloading of values from nested arrays within an array of data. import React, { useEffect } from "react"; export function loadComponent({ config, LayoutRenderer }) { const loadModules = (name) => q ...

Unique alphanumeric code following the inclusion of a JavaScript file

I'm encountering an issue with a webpage that incorporates two JavaScript files. When inspecting it using firebug, I noticed that every time the page loads, these two files are included with the prefix ?_=someRandomNumber I'm unsure about the or ...

The functionality of Vue.js routes is disrupted when employing the router-link component

I recently worked on a project using Vue.js. In the navbar, I added two menu options - Home and About, which are supposed to direct users to specific pages when clicked. Everything runs without any errors, but for some reason, the router doesn't navig ...

Is there a way to deactivate or dim a specific hour in an HTML time form?

I am currently facing a challenge with my booking form. I need to find a way to grey-out or disable the hours/times that have already been booked by previous customers. This will help ensure that the next person can select a different time slot. However, I ...