Home > OS >  How do I prevent the same set of error messages from showing after form submission in Vue.js?
How do I prevent the same set of error messages from showing after form submission in Vue.js?

Time:11-05

I am trying to display error messages when the form is submitted empty. However, the same error messages showed up based on the number of times I clicked the button. How do I show unique set of error messages instead of looping?

Here's how it looks:

enter image description here

Here's the code I have tried to check if form is empty:

 checkForm(){
   
    if (this.staffName && this.designation && this.staffId && this.skills) {
      return true;
    }
    if (!this.staffName) {
      this.errors.push('Staff Name required.');
    }
    if (!this.designation) {
      this.errors.push('Designation required.');
    }
    // if (this.password = '') {
    //   alert('Password required.');
    // }
    if(!this.staffId){
      this.errors.push('Staff ID required.')
    }
    if(this.skills === []){
      this.errors.push('Select at least one.');
    }
    if(this.errors.length){ 
      return this.errors
    }
    else{
      for (var staff of this.info){
        if(staff.staff_id == this.staffId){
          this.errors.push('This Staff exist! Please try again.');
          return this.errors
        }
        else{
          this.addStaff()
        }
      }
    }
  },

Here's the code I used to display the errors if the form is empty:

  <p v-if="errors.length">
      <b>Please correct the following error(s):</b>
      <ul>
        <li v-for="(error, idx) in errors" :key="idx">{{ error }}</li>
      </ul>
  </p>

CodePudding user response:

Easiest method I can think of:

Clear the array every time you fire the button

you can either do it on the template tag

<button 
  type="submit" 
  @click="errors = []"
>

or in the checkForm method

checkForm() {
  this.errors = [] //make sure to place it at the top
}

Mentionables

also, not within your question but you cannot compare array with ===, or even ==, it will always return false

I am referring to this

    if(this.skills === []){
      this.errors.push('Select at least one.');
    }

since you just want to know whether it is empty, use .length instead. But if you want to compare like

[1, 2] == [1, 2]

it will always return false, but you can google up the solution easily as it is very popular issue that JS developers face

CodePudding user response:

Instead of pussing error messages to array you can use Object or even if you want to stick with error you can use array include function to check if that already in array or not. Like:

if (!this.errors.includes('Staff Name required.');
{
    this.errors.push('Staff Name required.');
}

Or if you want to use Object you can do something like

data() {
   return {
      errors: {
           staf_name: null,
       }

   }
}

then in your code you can update it like this.errors.staf_name = '';

Thanks

  • Related