How to activate a button only if the specified conditions are met using VueJS 3

I'm currently facing challenges while working on a form to enable a button when certain conditions are met.

The form I created includes fields for name, phone number, options, and a message. Once all requirements are filled, I aim to re-enable the disabled submit button.

Any advice on how to successfully re-enable the button for form submission?

<template>

    <div class="contact">
  <h1>We appreciate all questions you may have regarding this application!</h1>
  <h2>Please leave a message below, and we will do our best to respond promptly!</h2>
</div>

  <form @submit.prevent="submitForm">
    <div class="form-control" :class="{invalid: fullNameValidation === 'invalid'}">
      <label for="name">Name</label>
      <input id="name" name="name" type="text" v-model="fullName" @blur="validateInput">
      <p v-if="fullNameValidation === 'invalid'">Please enter your name.</p>
    </div>
    <div class="form-control" :class="{invalid: phoneValidation === 'invalid'}">
      <label for="phone">Phone Number</label>
      <input id="phone" name="phone" type="number" v-model="phoneNr" @blur="validatePhone" pattern="[0-9]*">
      <p v-if="phoneValidation === 'invalid'">Please enter a valid phone number.</p>
    </div>
    <div class="form-control">
      <label for="referrer">How did you hear about this application?</label>
      <select id="referrer" name="referrer" v-model="referrer">
        <option value="" disabled hidden>Select an option</option>
         <option value="internet">Internet</option>
        <option value="friends">Friends</option>
        <option value="newspaper">Newspapers</option>
        <option value="other">Other</option>
      </select>
    </div>
    <div class="form-control" :class="{invalid: messageValidation === 'invalid'}">
      <label for="message">Message</label>
      <textarea name="message" id="message" cols="30" rows="10" v-model="message" @blur="validateMessage"></textarea>
       <p v-if="messageValidation === 'invalid'">Please enter your message.</p>
    </div>

    <div>
      <button v-on:click="$router.push('thankyou')" :disabled="!isComplete" id="myBtn">Send Message</button>
    </div>
  </form>
</template>

<script>
export default {
    data() {
        return {
            fullName: '',
            fullNameValidation: 'pending',
            phoneNr: 'null',
            phoneValidation: 'pending',
            referrer: '',
            messageValidation: 'pending'
        }
    },

    methods: {
        submitForm() {
            this.fullName = '';
        },
        validateInput() {
            if (this.fullName === '') {
                this.fullNameValidation = 'valid'
            } else {
               this.fullNameValidation = 'invalid'
            }
        },
        validatePhone() {
           if (this.phoneNr > 10) {
                this.phoneValidation = 'valid'
            } else {
                this.phoneValidation = 'invalid'
            }
        },
         validateMessage() {
            if (this.messageValidation > 1) {
                this.messageValidation = 'valid'
            } else {
                this.messageValidation = 'invalid'
            }
        },

        computed: {
       isComplete() {
          return Object.values(this.fields).every(({valid}) => valid)
      }
  }
    }
}
</script>

Answer №1

Combine all your form fields into one model, including the errors object.

Then utilize Object.keys to access known field keys for validation purposes.

export default {
  data() {
    return {
      form: {
        errors: {},
        values: {
          fullName: '',
          phoneNr: '',
          referrer: '',
        }
      }
    }
  },
  methods: {
    validate(field) {

      let fields = []
      // single field
      if (field) {
        delete this.form.errors[field]
        fields.push(field)
      } else {
        this.form.errors = {}
        // all fields
        fields = Object.keys(this.form.values)
      }


      if (fields.includes('fullName')) {
        if (this.form.values.fullName === '') {
          this.form.errors.fullName = 'Enter your full name'
        } else if (this.fullName !== some other validation) {
          ...
        }
      }

      if (fields.includes('phoneNr')) {
        if (this.form.values.phoneNr === '') {
          this.form.errors.phoneNr = 'Enter your phone number'
        }
      }

      if (fields.includes('referrer')) {
        if (this.form.values.referrer === '') {
          this.form.errors.referrer = 'Enter referrer'
        }
      }

      // if errors is empty return true
      return !Object.keys(this.form.errors).length
    },
    submit() {
      // validate all
      if (this.validate()) {
        // do some thing, form is valid, if native form handler, return true/false
      }
    }
  }
}
<div class="form-control" :class="{invalid: form.errors.fullName}">
  <label for="name">Name</label>
  <input id="name" type="text" v-model="fullName" @blur="validate('fullName')">
  <p v-if="form.errors.fullName">{{ form.errors.fullName }}</p>
</div>

If you don't specifically need the @blur validation, it simplifies things quite a bit and its pretty standard to do validation on submit rather than on blur of individual fields.

export default {
  data() {
    return {
      form: {
        errors: {},
        values: {
          fullName: '',
          phoneNr: '',
          referrer: '',
        }
      }
    }
  },
  methods: {
    validate() {

      this.form.errors = {}

      if (this.form.values.fullName === '') {
        this.form.errors.fullName = 'Enter your full name'
      } else if (this.form.values.fullName !== some other validation) {
        ...
      }

      if (this.form.values.phoneNr === '') {
        this.form.errors.phoneNr = 'Enter your phone number'
      }


      if (this.form.values.referrer === '') {
        this.form.errors.referrer = 'Enter referrer'
      }


      // if errors is empty return true
      return !Object.keys(this.form.errors).length
    },
    submit() {
      if (this.validate()) {
        // do something, form is valid, if native form handler, return true/false
      }
    }
  }
}
<div class="form-control" :class="{invalid: form.errors.fullName}">
  <label for="name">Name</label>
  <input id="name" type="text" v-model="fullName">
  <p v-if="form.errors.fullName">{{ form.errors.fullName }}</p>
</div>

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

Transforming DOM elements into Objects

Here are some values that I have: <input name="Document[0][category]" value="12" type="text"> <input name="Document[0][filename]" value="abca.png" type="text" > I am looking for a way to convert them into an object using JavaScript or jQuer ...

Vue.js and Symfony: How to Handle Null Images

Having trouble uploading an image to the server from Vue.js. On the server side, I'm having difficulty retrieving the image as it always returns null. Below is the Vue.js code snippet: submitFile() { let formData = new FormData(); ...

In React js, automatically insert a new row into a table once the Dialog window has

I am currently exploring Reactjs and using Material UI Dialog to implement a dialog box for users to input information and interact with a POST API. After the process is completed, the dialog closes but I would like to dynamically display the added informa ...

Assistance required in translating Firebase syntax from version 7.15.1 to version 9.6.1

I'm embarking on my Firebase journey and trying to follow a tutorial that seems to be a bit outdated. I could use some assistance in updating the code to match the newer version, as it appears the syntax has changed. The tutorial uses Firebase 7.15.1, ...

What advantages can be gained by opting for more precise module imports?

As an illustration, consider a scenario where I have an Angular 6 application and need to bring in MatIconModule from the @angular/material library. Two options could be: import { MatIconModule } from '@angular/material/icon'; Or import { Mat ...

What is the best way to display three unique maps simultaneously on separate views?

In this scenario, I have incorporated three separate divs and my goal is to integrate three maps into them. The javascript function that controls this process is as follows: function initialize() { var map_canvas1 = document.getElementById('map_canva ...

Invoke two functions simultaneously on a single Onchange event

Can someone help me understand how to trigger two functions by changing the value of a specific dropdown list using the "OnChange" event in Ajax? Note: The system typically only displays the output of the showhistory() function. Here is my existing code: ...

Vue Labyrinthine Design theme

Looking for some guidance from experienced developers out there! I'm currently exploring how to incorporate Mazeletter as a background feature for each page in an app project I've been working on. This is all new territory for me, so any assista ...

Using the power of jQuery, execute a function only once when the element is clicked

My goal is to use jQuery's .one method to change the color of an element only once, even if clicked again. However, I am having trouble getting it to work properly. Here is my HTML: <!DOCTYPE html> <head> <meta charset="UTF-8"& ...

Adjusting the minimum value on a textfield with JQuery Validate plugin in real-time

I am attempting to dynamically update the minimum value on one field based on input from other fields. Here is a brief overview of my code: $("#new_project").on("click", function() { switch($('input:radio[name=quality-level]:checked').val() ...

Tips for designing a button that can execute a JavaScript function repeatedly

My goal is to rotate the numbers clockwise when the rotate button is clicked. I have included all the relevant code. I have created a button that triggers a javascript function when clicked. The problem is that the function only rotates the numbers once. ...

Having trouble getting Vue async components to function properly with Webpack's hot module replacement feature

Currently, I am attempting to asynchronously load a component. Surprisingly, it functions perfectly in the production build but encounters issues during development. During development, I utilize hot module replacement and encounter an error in the console ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

While attempting to utilize inner class functions in Node JS, an error is being encountered

I've been delving into Node JS and exploring how to implement an OOP structure within node. I've created a simple class where I'm using functions to verify and create users in a database. However, I'm encountering a TypeError when attem ...

Capture all Fetch Api AJAX requests

Is there a way to intercept all AJAX requests using the Fetch API? In the past, we were able to do this with XMLHttpRequest by implementing code similar to the following: (function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.p ...

Ways to extract information from an Object and save it into an array

In my Angular2 project, I am working on retrieving JSON data to get all the rooms and store them in an array. Below is the code for the RoomlistService that helps me fetch the correct JSON file: @Injectable() export class RoomlistService { constructor( ...

rearranging items from one list to another list

I've encountered an issue in my HTML code that I need help with. I have included some classes for clarity, but their specific names are not essential. My goal is to make the "sub-nav" element a child of the "mobile parent" list item on mobile devices. ...

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...

Controller using the 'as' syntax fails to add new object to array

Lately, I've been experimenting with the Controller as syntax in Angular. However, I seem to be struggling to grasp its functionality. I am currently following a tutorial that utilizes $scope to bind the members of the controller function rather than ...

Issues with npm @material-ui/core Button and TextField functionality causing errors and failures

I'm currently working on a React project and decided to incorporate the material-ui framework. After creating a component that includes a textfield and a button, I've encountered an issue where I can't interact with either of them as they s ...