VueJS form validation does not account for empty inputs in both fields

One of the challenges I'm facing is generating a form with Vue.js using the input fields below:

{
      name: 'first_name',
      type: 'text',
      label: 'First Name',
      placeholder: 'First Name',
      required: true,
      validation_message: 'First name is required'
    },
    {
      name: 'email',
      label: 'Email',
      type: 'email',
      placeholder: 'Email',
      required: true,
      validation_message: 'Email is required'
    }

To create the input field, I've implemented it this way:

    <input
      :type="inputField.type"
      :placeholder="inputField.placeholder"
      :name="inputField.name"
      :id="inputField.name"
      v-model="userData[inputField.name]"
    />

I have initialized the data like so:

data() {
    return {
      userData: {
        [this.inputField.name]: ""
      },
      isInputFieldRequired: this.inputField.required,
      isInputFieldEmpty: false
    };
  }

For checking if the input is empty, I have set up methods as follows:

methods: {
    checkIfInputFieldEmpty: function() {
      if (this.userData[this.inputField.name] === "") {
        return (this.isInputFieldEmpty = true);
      }
      this.isInputFieldEmpty = false;
    },
    checkIfRequiredFiledEmpty: function() {
      const { name, required } = this.inputField;
      return required && this.userData[name] === "";
    }
  }

The issue I am facing is that when either of the fields is not empty, the form is submitted. How can I resolve this particular problem?

Answer №1

To enhance your form functionality, consider utilizing Computed Properties and incorporating a value field within your inputFields. To determine if the form can be submitted, you may employ the every method:

var app = new Vue({
    el: '#app',
    data: {
      inputFields: [
        {
          name: 'first_name',
          type: 'text',
          label: 'First Name',
          placeholder: 'First Name',
          required: true,
          validation_message: 'First name is required',
          value: null,
        },
        {
          name: 'email',
          label: 'Email',
          type: 'email',
          placeholder: 'Email',
          required: true,
          validation_message: 'Email is required',
          value: null,
        }
      ],
    },
    computed: {
      allowSubmitForm: function(){
            return this.inputFields.every(
              inputField => inputField.value != null 
              && inputField.value != undefined
              && inputField.value != '');
        }
    }
  })
<div id="app">
   <form>
      <input v-for="inputField in inputFields"
      :type="inputField.type"
      :placeholder="inputField.placeholder"
      :name="inputField.name"
      :id="inputField.name"
      v-model="inputField.value" />
      <button type="submit" :disabled="!allowSubmitForm">Submit</button>
   </form>
</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

The function correctly identifies the image source without error

I possess a pair of images: <img id="img1" src="l1.jpg" usemap="#lb" height="400" border="0" width="300"> <img src="images.jpg" id="img2"> Next up is some JavaScript: function validateImages () { if (document.getElementById('img2&ap ...

Using JQuery Datatables to output HTML based on JavaScript conditional logic

I am presently working on a project that involves using JQuery Datatables to display my data. Within this project, I am utilizing the datatables render method to format the data before it is displayed. However, I have encountered a challenge where I need t ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

The issue arises with the Google Map marker failing to function correctly when pulling data

I've recently started learning Google Maps. It's interesting that markers work and are displayed when statically declared, but not when retrieved from a database. // var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.69 ...

Transforming jQuery Object into a String after making an AJAX request

If I were to submit a form with some text in the value of user_input, let's say "I am free," through AJAX, and it comes back to me as a string. Once it becomes an Object, how could I convert it back into a string format? Thanks, <!DOCTYPE HTML> ...

Is it worth diving into Vue.js, Angular, or React while utilizing Laravel currently?

After spending 2 months immersing myself in Laravel, I am considering expanding my skills by learning a JavaScript framework. While I have discovered that Laravel comes bundled with Vue.js, there are also options like Angular and React.js which are more po ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

Retrieving over 300,000 rows from elasticsearch and saving them as a .csv document

Hi there, I am currently working on a website in nodejs that utilizes an Elasticsearch database. One of my indexes, 'bigData*', contains 366,844 rows with each row consisting of 25 items, each being a different string of varying sizes (with a max ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Problem with React Native Camera: Camera display is not functioning correctly - React-Native-Vision-Camera Error

Hey there! I could really use some help with a tricky situation I'm facing in my React Native app, specifically regarding camera integration. Here's the scoop: The Issue: I'm working on a video recording application using React Native that ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

Guide to verify the user selection within a select form

Here is a form with a select field: <form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt"> <select style="background: transparent; border-bottom:5px;" name="subname" class="required"> ...

Incorporating CSS animations into Vue.js while an API call is being made

When a specific icon is clicked, an API call is triggered: <i class="fas fa-sync" @click.prevent="updateCart(item.id, item.amount)"></i> I am looking to add an animation to rotate the icon until the API call is complete or ...

Issue: Unspecified error when trying to access object attribute in Vue (Nuxt)

I am facing an issue with my 'region' object. It appears to be displayed correctly with all its attributes, but when I try to access specific attributes, it shows up as 'undefined'. const region = { "id": 7, "name": ...

Dynamically uploading an HTML file using AJAX

My webpage has a feature that dynamically creates HTML with drop down elements. Additionally, there is a "create File" button on the page. The goal is for this button to trigger an AJAX POST request and upload the dynamic page created with drag and drops a ...

Change the class of each item in a list individually by hovering over them with the mouse using JavaScript

How to toggle classes in a list item one by one using the mouseover event in JavaScript? const items = document.querySelectorAll("ul li"); let currentItem; for (const item of items) { item.addEventListener("mouseover", e => { currentItem &am ...

Using Javascript and CSS to Float DIV Elements

Recently, I've been working on a small algorithm that adds a special class to an element when the mouse reaches the halfway point or beyond on the X-axis of the browser. I also have a screenshot that demonstrates where this application will be utiliz ...

Utilizing React's useState to store data in local storage

I am trying to figure out how to save data from a photos database API into local storage using the useState hook in React. Despite my attempts, I have not been successful with the useState method as the data in local storage gets cleared upon page refres ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

Improving Javascript Arrays for Easier Reading

A dataset has been organized into a table format as shown below: +------+---------+----+----+----+----+-------+----------+ | Year | Subject | A | B | C | F | Total | PassRate | +------+---------+----+----+----+----+-------+----------+ | 2015 | Maths ...