What is the best way to verify changing input fields in vue.js?

Validation of input fields using vuelidate is essential. The input field in question is dynamic, as the value is populated dynamically with jsonData through the use of v-model.

The objective:

Upon blur, the goal is to display an error if there is one; however, when typing inside the input field, no errors are shown.

My current approach involves the following for the input field:

    <div v-for="data in displayProfileData" :key="data.email" >
     <p>{{data}}</p>
   <div class="row">
       <div class="form-group col-xs-6 col-sm-6 col-md-6 col-lg-3">
                        <label for="phoneNo">Name</label>
              <input v-model="data.businessname"
              @blur="$v.form.name.$touch()"
              type="text" 
                            class="form-control" name="name"
                            id="name">
             <div v-if="$v.form.name.$error" class="form-error">
               <span v-if="!$v.form.name.required" class="text-danger">nameis required</span>
             </div>
                    </div>
          <p>{{$v}}</p>
   </div>
     </div>

To monitor changes, I display $v on the UI, but unfortunately, no modifications are detected when typing in the input field.

Regarding my script code:

    <script>
import { required,minLength } from 'vuelidate/lib/validators'
import axios from '../../services/base-api'
export default {
    data (){
      return{
          form :{
        name:''
          },
           displayProfileData:[]
      }
  },
  validations: {
    form: {
      name:{required}, 
    }
  },
  created(){
        this.userId = localStorage.getItem('user-Id')
        axios().post('/api/v1/Profile/getProfileData',this.userId)
        .then(res=>{
                console.log(res.data)
                this.displayProfileData=res.data

})
.catch(err=>{
    this.$toasted.error(err,{duration:2000})
})

}
}
</script>

The server provides data in the format

{ "businessid": "8126815643", "businessname": "manish",}

Issue: Initially, when the page loads, the input field displays manish. However, upon changing it and focusing out, an error message stating name is required appears. The cause of this issue remains unclear.

2:Dynamic Form- Check Here

Please review https://i.stack.imgur.com/OLRF7.png

Answer №1

As per the guidelines provided in the vuelidate documentation, it is recommended to implement the following updates:

<div v-for="data in $v.displayProfileData.$each.$iter" :key="data.email">
  ...
  <input  v-model="data.businessname.$model"
          @blur="data.businessname.$touch()"
          type="text"
          class="form-control"
          name="name"
          id="name"
  >
  <div v-if="data.businessname.$error" class="form-error">
     <span v-if="!data.businessname.required" class="text-danger">name is required</span>
  </div>
...
</div>
 validations: {
    displayProfileData: {
      //required,
      //minLength: minLength(1),
      $each: {
        businessname: { required }
      }
    }
 }

Here is the link to my codesandbox example for reference: sandbox link

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

Is there a way to transform this pledge back into a JSON array format?

My goal with this code is to retrieve a JSON array from my server. var students_list; const library_address = 'http://localhost:17330' async function fetchData(param1, param2) { if(param1 == 'getdata') { const response ...

Is it possible to utilize the maximum value from the store in Vuelidate while implementing Vue?

Utilizing VUE and Vuelidate for form input validation, specifically within a modal popup that retrieves data through ...mapGetters from the store. When static values are set like this, it functions correctly : validations: { refundAmount: { ...

Vue failing to render content from data object

I recently started using NuxtJs and decided to create a new file named test.vue within the pages directory. Below is the code snippet from my test.vue file: <template> <div> <h1 style="font-size: 30px">{{ message }} </h1> ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

VSCode is experiencing issues with recognizing .env* files for markup purposes and is also failing to recognize .env.local.* files

Current Environment: Utilizing NextJs, React, and VsCode Noticing a problem with syntax highlighting in my VSCODE editor. I have installed the following extensions: ENV DotEnv As per suggestions, I updated my json configuration file as follows: " ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

SequelizeDatabaseError: The operation could not be executed as there is no operator that allows for

I am attempting to create a join between two tables using UUIDs (also have IDs), and the relationships between these tables are quite complex... However, I encounter an error when running the query. The first table is named users, with its UUID labeled a ...

Obtain the AJAX response in separate div elements depending on whether it is successful or an error

Currently, my jQuery script outputs the result in the same div for error or success messages: HTML <div id="error-message").html(res); JQUERY jQuery('#register-me').on('click',function(){ $("#myform").hide(); jQuery ...

Identifying all Images with JavaScript, Including Asynchronous Ones

Is it possible to use JavaScript to identify all images within a document, even those that are loaded asynchronously (possibly after the DOM is fully loaded)? I am interested in developing a function that can determine if Google Analytics has been loaded ...

JavaScript substring() function in clone is experiencing an error

I am currently working on a JavaScript function that determines whether a specific substring is present in a larger main string. For instance, if the main string is "111010" and the substring is "011," the expected result should be false since the substr ...

Shifting the data label on a pie chart in ApexCharts - what's the trick?

I need help adjusting my data labels to make them more readable by moving them inward. It would be perfect if there is a way to dynamically center them within the slice. https://i.stack.imgur.com/bCelP.png Despite reading the documentation and trying dif ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

How can I update an Object's property changes in a Vue DOM element?

I am trying to display the status of an object's property in my DOM element. I have added a property called id to the object and when I use console.log, it shows as true. However, the update is not reflected in the DOM element. How can I make sure tha ...

What is the best way to modify the URL path to eliminate a specific parameter?

Recently, I integrated authentication into my Vue.js application utilizing Amazon AWS Cognito. Although the authentication is functioning properly, I am looking to tidy up the URL and so far have not been successful in doing so. Following authentication w ...

Update the page with AJAX-loaded content

I am currently utilizing a .load() script to update the content on a webpage in order to navigate through the site. This is resulting in URLs such as: www.123.com/front/#index www.123.com/front/#about www.123.com/front/#contact However, I am encountering ...

Error: The function `push` cannot be used on the variable `result` (TypeError)

Here is a snippet from my react component const mockFetch = () => Promise.resolve({ json: () => new Promise((resolve) => setTimeout(() => resolve({ student1: { studentName: 'student1' }, student2: { studen ...

Do we need to handle promise resolution after sending a response to the client?

After sending the response to the client, I have a requirement to execute an asynchronous function. res.json({}); someAsyncFunction(); //this function does not require await Is it considered problematic to call this function without awaiting its promise? ...

Current CORS complications persisting with Vue 3, Axios, and ASP.NET Core Web API backend interaction

I am puzzled. While running my .net core server and loading the vue project in the same file, I encounter partial success. However, when I start testing the axios/fetch requests, the test project fails in other ways. My CORS policy is set to be very lenie ...