I am using Veevalidate and Buefy to validate a form before a POST request. I am able to validate the form correctly, but the POST request method runs before the validation.

I am getting a bit confused on how to call the methods in order:

  1. Validate form
  2. POST request

Codesandbox: https://codesandbox.io/s/mj1vy2vq0j

Code overview

<b-modal>
  <form @submit.prevent="validateBeforeSubmit">
    ...
    ...
    <button type="submit" class="button is-primary" @click="postItem()">Submit</button>
    <button type="button" class="button" @click="isAddModalActive=false">Cancel</button>
  </form>
</b-modal>

<script>

...

methods: {
  validateBeforeSubmit() {
    this.$validator.validateAll().then(result => {
      if (result) {
        this.$toast.open({
          message: "Form is valid!",
          type: "is-success",
          position: "is-bottom"
        });
      }
      this.$toast.open({
        message: "Form is not valid! Please check the fields.",
        type: "is-danger",
        position: "is-bottom"
      });
    });
  },
  postItem() {
    alert("postItem function was called");
  }
}
</script>

1 Answers

1
Ninth Autumn On

You can call your submit function in your validateBeforeSubmite() function

methods: {
  validateBeforeSubmit() {
    this.$validator.validateAll().then(result => {
      if (result) {
        this.$toast.open({
          message: "Form is valid!",
          type: "is-success",
          position: "is-bottom"
        });
       this.postItem()// call your post function here and remove from @click in your submit button
      }
      this.$toast.open({
        message: "Form is not valid! Please check the fields.",
        type: "is-danger",
        position: "is-bottom"
      });
    });
  },
  postItem() {
    alert("postItem function was called");
  }
}