Vue JS - Troubleshooting Checkbox Validation Error During Form Submission

When a user fills out my registration form, there is a checkbox to confirm acceptance of the terms and conditions. Currently, the validation error for this checkbox appears immediately upon hitting submit, even though the checkbox starts as unchecked. The error disappears once the checkbox is ticked, but I want the validation error to only show up after clicking submit (if the checkbox remains unchecked). I am not seeing any specific console errors, just struggling with the execution. Can anyone guide me on how to achieve this desired behavior? Any help would be greatly appreciated!

Checkbox.vue - Component representing the checkbox.

<template>
  <div class="check-wrapper">
    <label :for="id" class="check-label">
      <input v-model="checkboxValue"
             :id="id"
             :checked="isCheckboxChecked"
             :oninput="checkCheckbox()"
             type="checkbox"
             name="newsletter"/>
      <span v-if="labelText && !isLabelHtmlText">{{ labelText }}</span>
      <span v-if="labelText && isLabelHtmlText" class="label-html" v-html="labelText"></span>
      <span :class="{'check-mark-error': checkboxError}" class="check-mark"></span>
    </label>
    <p v-if="checkboxError" class="checkbox-error text-error">{{checkboxError}}</p>
  </div>
</template>

<script>
  data: () => ({
    checkboxValue: false
  }),
  methods: {
    updateValue: function () {
      if (this.$props.callback) {
        this.$props.callback(this.$props.id, this.$props.checkboxData, this.checkboxValue);
      }
    },
    checkCheckbox: function () {
      this.updateValue();
    }
  }
</script>

Register.vue - Parent component handling the registration process.

<template>
   <BasicCheckbox :id="'terms-privacy'"
                  :callback="onTermsClick"
                  :label-text="'terms and conditions'"
                  :is-label-html-text="true"
                  :checkbox-error="termsPrivacyError"
                  class="terms-privacy"/>
</template>
<script>
  methods: {
    validateData: function (data) {
      if (!this.termsPrivacyError) {
        this.sendRegistration(data).then(response => {
          if (response) {
            console.log('Registration successful');
            this.loginUser({email: data.email, password: data.password}).then(response => {
              if (response) {
                console.log('User logged in!');
                this.$router.push({name: ROUTE_NAMES_HOME.HOME});
              }
            })
          }
        });
      }
    },

    // Terms and Privacy Checkbox
    onTermsClick: function (checkboxId, checkboxData, data) {
      this.termsPrivacyError = !data ? termsPrivacyErrorText : '';
    },
  }
</script>

Answer №1

Initially, this solution may not be the most sophisticated, but it does the job. By utilizing a computed value, we can determine when to display an error message. This value is updated in the submit method and reset when the checkbox is clicked for demonstration purposes.

new Vue({
  el: "#app",
  data: {
    termsState: false,
    validated: false
  },
  computed: {
    termsError() {
      return this.validated && !this.termsState
    }
  },
  methods: {
    handleTermsState() {
      this.validated = false
    },

    handleSubmit() {
      this.validated = true
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <label for="terms">
            Terms and Privacy Policy
            <input type="checkbox" id="terms" name="terms" v-model="termsState"  @change="handleTermsState">
            {{ termsState }}
        </label>
  <p style="color: red" class="for-error terms-error" v-if="termsError">You have to agree the terms and privacy condition.</p>
  <div><button type="submit" @click="handleSubmit">Submit</button></div>
</div>

Answer №2

The issue in your scenario seems to be related to the validation not triggering when the user fails to check the privacy and policy checkbox. However, if the user clicks on and off the checkbox, the validation works as expected.

To address this issue, you can inspect the data property "checkboxValue" of the child component "Checkbox.vue". This property defaults to false but switches to true once the user interacts with the checkbox. Before submitting the form, ensure to include a check for the checkboxValue.

Below is the revised content of the Register.vue component file:

<template>
  <BasicCheckbox
    :id="'terms-privacy'"
    :callback="onTermsClick"
    :label-text="'terms and conditions'"
    :is-label-html-text="true"
    ref="BasicCheckbox"
    :checkbox-error="termsPrivacyError"
    class="terms-privacy"
  />
</template>
<script>
methods: {
  validateData: function (data) {
    if (!this.termsPrivacyError && this.$refs.BasicCheckbox.checkboxValue) {
      this.sendRegistration(data).then(response => {
        if (response) {
          console.log('Registration successful');
          this.loginUser({email: data.email, password: data.password}).then(response => {
            if (response) {
              console.log('User logged in!');
              this.$router.push({name: ROUTE_NAMES_HOME.HOME});
            }
          })
        }
      });
    }
  },

  // Terms and Privacy Checkbox
  onTermsClick: function (checkboxId, checkboxData, data) {
    this.termsPrivacyError = !data ? termsPrivacyErrorText : '';
  },
}
</script>

Changes made:

I included the ref attribute for the 'BasicCheckbox' component stage like so:

ref="BasicCheckbox"

In the validation logic, I simply added a condition to check if the 'BasicCheckbox' component's value is set to `true':

if (!this.termsPrivacyError && this.$refs.BasicCheckbox.checkboxValue)

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

Error message: "Azure deployment encounters Vue CSS dependency missing issue"

I recently built a Vue app following this tutorial but without CRUD functionality: . The app was created using Vue CLI 4.3.1 with vue create. During local development, it runs smoothly with npm run serve and builds without any errors. Now, I'm atte ...

The request from localhost:3000 to localhost:3003 could not be proxied by ReactJS

Currently, I am working on developing a Single Page Application (SPA) using create-react-app with an expressjs server as the backend. During development, my frontend test server runs on port 3000 while my backend expressjs test server runs on port 3003. T ...

Tips for incorporating an onClick event into a variable beyond the class extension

Currently utilizing React/Redux in this scenario. At the beginning of my code, outside of the class extends block, I have: const Question10 = () => (<div> <p>Insert question here</p> <input place ...

Steps to create an instance method that only accepts the name of another instance method

I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them? Let's t ...

Utilizing JavaScript's Array.sort() method for sorting objects with varying properties

Currently, I am dealing with these specific Objects: let obj1 = { from: Date, to: Date } let obj2 = { date: Date } These Objects have been placed in an Array: let arr = [ obj1, obj2 ] My goal is to organize the objects within the array by using arr.sort( ...

React is throwing an error that says, "You cannot use the import statement outside a

My journey with learning React has just begun. I followed the steps outlined in the starting guide at https://react.dev/learn/add-react-to-an-existing-project, but unfortunately, I encountered an error: "Cannot use import statement outside a module." Here ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...

Ensure that JavaScript functions are executed sequentially without overlapping

Important : Absolutely no jQuery allowed I have developed four distinct functions and I am looking to execute them sequentially, one after the other in JavaScript without using jQuery. I have scoured the internet for a solution but unfortunately have not ...

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: this.$root.$emit('new-mess ...

A guide to entering information into an input field with JavaScript for logging in successfully

https://i.stack.imgur.com/TF51Z.gif https://i.stack.imgur.com/HHsax.png https://i.stack.imgur.com/HUztt.png When attempting to input text using document.getelement('').value="" , it doesn't behave as expected. The text disappear ...

Comparing elements in one array to elements in another array

In AngularJS, the $scope.categories array is populated from a multi-select element. $scope.categories = ["Adventure", "Strategy"] To compare this array with the categories in the items array below: $scope.items = [ { title: "Star Wars", ...

Using parameters in Vue router

Having some trouble here. Can't seem to make it work. I've got this component called Project. Inside, there's this block of code: When I click on project, I want it to navigate to another detail page but nothing happens: {path: '/det ...

Exploring the capabilities of NodeJS together with the fetch function of Backbone

I have a code snippet for the front-end using fetch: var MyModel = Backbone.Model.extend(); var MyCollection = Backbone.Collection.extend({ url: '/questions', model: MyModel }); var coll = new MyCollection(); ...

Posting data using the form method="post" in Vue does not seem to be working

My goal is to create a website that allows users to reserve a seat using a specific password and time slot. I've set up a form where users can input the password and their name, then submit the form to make the reservation. However, I'm facing an ...

The code functions properly on React Webpack when running on localhost, however, it fails to work once deployed to AWS Amplify

As I work on my React.js app, I encountered an issue with hosting pdf files on Amplify. While everything runs smoothly on localhost/3000, allowing me to access and view the pdf files as desired either in a new tab or embedded with html, the same cannot be ...

Unable to locate the React Native variable named "NetworkStatus"

I have been working on implementing a code to test internet connectivity using react native NetInfo from '@react-native-community/netinfo'. Unfortunately, I keep running into an error that says "Can't find variable: connectionStatus&quo ...

Password validation with Mongoose customization

I'm working on creating a Schema using mongoose, but I'm facing some challenges when it comes to implementing custom validation for the password. The password should meet the following criteria: It must contain at least one special character ...

What is the preferred workflow for client-side modules: (Browserify + npm + gulp) or (RequireJS + Bower + gulp)?

As I delve into various client-side Javascript modules workflows for my current Node.JS Express project, I find myself torn between Browserify + npm + gulp and RequireJS + Bower + gulp. While I lean towards CommonJS due to its syntax, the idea of sharing ...