Home > Software engineering >  Submit form free when from errors in VueJs
Submit form free when from errors in VueJs

Time:05-26

I'm currently building a form in Vue and I'm having a hard time submitting the form when the form is free from error messages.

I'm currently fixed so that the errors show when they should but the goal is to change the page after pressing the submit button.

I would appreciate any tip that could help me :)

HTML

<template>
  <form @submit.prevent="submitMessage">
    <div >
      <label for="user-name">Name*</label>
      <input id="user-name" name="user-name" type="text" v-model="userName" />
    </div>
    <div >
      <label for="age">Age</label>
      <input id="age" name="age" type="number" v-model="userAge" />
    </div>
    <div >
      <label for="email">Email*</label>
      <input id="email" name="email" type="email" v-model="email" />
    </div>
    <div >
      <label for="referrer">How did you hear about us?</label>
      <select id="referrer" name="referrer" v-model="referrer">
        <option value="google">Google</option>
        <option value="wom">Word of mouth</option>
        <option value="newspaper">Social Media</option>
        <option value="other">Other</option>
      </select>
    </div>
    <div >
      <label for="message">Message*</label>
      <textarea rows="5" cols="50" id="message" name="message" v-model="message">Aa</textarea>
    </div>
    <div>
      <button id="send" @click="sendForm()">Send Message</button>
    </div>
    <div >
      <p v-if="errors.length > 0">
        <b>Please correct the following error(s):</b>
        <ul>
          <li v-for="error in errors">{{ error }}</li>
        </ul>
      </p>
    </div>
  </form>
</template>

Vue

<script>

export default {
  data() {
    return {
      userName: '',
      userAge: null,
      referrer: 'google',
      email: '',
      message: '',
      errors: []
    };
  },
  methods: {
    submitMessage(e) {
      this.userName = '';
      this.userAge = null;
      this.email = '';
      this.referrer = 'google';
      this.message = ''
    },
    sendForm() {
      this.errors = [];
      if (!this.userName) {
        this.errors.push('Name is required');
      }
      if (!this.email) {
        this.errors.push('Email is required');
      } else if (!this.validEmail(this.email)) {
        this.errors.push('Valid email required.');
      }
      if (!this.message) {
        this.errors.push('Message is required');
      }
      if (!this.errors.length) {
        return true;
      }
      if (this.errors.any()) {
        this.$router.push('/thankyou');
      }
    },
    validEmail: function (email) {
      var re = /^(([^<>()\[\]\\.,;:\s@"] (\.[^<>()\[\]\\.,;:\s@"] )*)|(". "))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/;
      return re.test(email);
    }
  }
}

</script>

Router.js

import {
    createRouter,
    createWebHistory
} from 'vue-router';


import HomeBeerSearch from './pages/beers/HomeBeerSearch.vue';
import BeerList from './pages/beers/BeerList.vue';
import CustomerSupport from './pages/contact/CustomerSupport.vue';
import ThankYou from './pages/contact/ThankYou.vue'

const router = createRouter({
    history: createWebHistory(),
    routes: [{
            path: '/',
            component: HomeBeerSearch
        },
        {
            path: '/beers',
            component: BeerList
        },
        {
            path: '/support',
            component: CustomerSupport
        },
        {
            path: '/thankyou',
            component: ThankYou
        }
    ]
});

export default router

CodePudding user response:

You can change the page by Vue router on SPA:

this.$router.push({ name: 'route name' })

or you can use raw JavaScript for external links:

window.location.href = 'http://www.google.com';

CodePudding user response:

    // there is no such function errors.any()
    if (this.errors.any()) {
        this.$router.push('/thankyou');
    }

Your doing the navigation correctly but I think that the if statment logic is a little flawed. Try this instead:

    // check if there are errors; if not go to the thank you page
    if (!this.errors.length) {
         this.$router.push('/thankyou');
    }
  • Related