[Vuejs]-Form validation for email not working in Vuejs

1πŸ‘

βœ…

To t the error message dynamically you need to use watchers or computed values. For this purpose, computed values is probably the better choice. Try this

<form 
    class="footer-form" 
    id="footerform-details" 
      @submit="checkForm" 
      action="#"
      method="post"
  >
    <div class="form-group" id="footerbtn-tooltip">
      <input 
        type="email" 
        class="form-control" 
        placeholder="Your Email Address"        
        v-model="email"
      >
      <button type="submit">Submit</button>
    </div>
    <p v-if="errors.length">
      <b>Please enter the following input value</b>
      <ul>
        <li v-for="error in errors">{{ error }}</li>
      </ul>
    </p>
  </form>

We leave the submit method as is. and add a computer property. This will react everytime user enters a letter.

var subscribe = new Vue({

  el: '#footerform-details',
  data: { email: null },
  methods: {
    checkForm: function (e) {
      e.preventDefault();
      if (this.email) { return true; }

      this.errors = [];

      if (!this.email) {
        this.errors.push('Email required.');
      } 
    }
  },
  computed: {
     errors: function() {
        if (!this.email) {
          return ['Email required.']; // can make it [...this.errors, 'Email required.']
        } else {
          return []
        }
     }
  },
})

let me know if this works, there are more optimizations possible. If its a subsribe email form then it will always be one input, so you could convert error to an object or just a string clearing up your htmp v-for statement as well.

πŸ‘€Varun Agarwal

1πŸ‘

I think you have to reset this.errors = []; before if(this.email) like

methods: {
    checkForm: function (e) {
        this.errors = [];
        if (this.email) {
            return true;
        }



        if (!this.email) {
            this.errors.push('Email required.');
        } 
        e.preventDefault();
    }
},
πŸ‘€Vibha Chosla

1πŸ‘

Writing validation rules for input fields is not always a best practice.

I suggest to use https://www.npmjs.com/package/vee-validate package.

Import plugin in main.js
Then use it as shown below.

Make sure to give name to element which you want to validate

<template>
<div>
    <input type="text" v-model='email' name="email" v-validate="'required|email'"/>
    <span v-if="errors.has('email')">{{errors.first('email')}} </span>  
    //..you don't have to create any errors array plugin will do it.
</div>
</template>
<script>
   export default{
        data(){
         email:null,
        }
   }
</script>

Now you dont have to write any validation rules yourself.
v-validate will create an array of errors and show those errors if they occur.

πŸ‘€Afraz Ahmad

Leave a comment