Vue JS - Show validation error message for checkboxes upon submission

I am encountering an issue with my registration form. I have a checkbox that needs to be validated when the submit button is clicked. The problem is, the validation error appears immediately because the checkbox starts off unselected. I would like the validation error to show up only after hitting submit if the checkbox is not checked. Although there are no console errors, I am having trouble with the execution. Can someone provide guidance on how to resolve this? Any assistance would be greatly appreciated!

This code snippet shows the Checkbox.vue component:

<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>

And here is some code from Register.vue, which is the parent component for 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>
  const termsPrivacyErrorText = "checkmark is not checked";

  data: () => ({
    termsPrivacyError: '',
  }),

  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

I have developed simplified versions of the components to illustrate how the desired functionality can be implemented.

CheckboxAgree.vue

<template>
  <div class="checkbox-agree">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" v-model="agreed" @change="processAgree" id="checkbox2">
      <label class="form-check-label" for="checkbox2">
        Agree to terms
      </label>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        agreed: false
      }
    },
    methods: {
      processAgree() {
        this.$emit('terms-agreed-event', this.agreed)
      }
    }
  }
</script>

Signup.vue

<template>
  <div class="signup">
    <h4>Sign Up</h4>
    <div class="row">
      <div class="col-md-6">
        <form @submit.prevent="submitForm">
          <checkbox-agree @terms-agreed-event="processCheckboxAgree" />
          <button type="submit" class="btn btn-primary">Register</button>
          <span v-if="displayAlert" class="alert">Please agree to terms</span>
        </form>
      </div>
    </div>
    <h5 v-if="displayConfirmation">Registration successful!</h5>
  </div>
</template>

<script>
  import CheckboxAgree from './CheckboxAgree';

  export default {
    components: {
      CheckboxAgree
    },
    data() {
      return {
        termsAgreed: false,
        displayAlert: false,
        displayConfirmation: false
      }
    },
    methods: {
      processCheckboxAgree(agreed) {
        this.termsAgreed = agreed;
        this.displayAlert = false;
      },
      submitForm() {
        if (!this.termsAgreed) {
          this.displayAlert = true;
        }
        else {
          this.displayConfirmation = true;
        }
      }
    }
  }
</script>

<style scoped>
  .alert {
    color: red;
    margin-left: 1rem;
  }
</style>

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 displayed: "The timer function encountered an issue as second_input is found to be null."

var idinterval; var second_input_value = document.getElementById("Seconds"); var minute_input_value = document.getElementById("Minutes"); var second_val = second_input_value.value; var minute_val = minute_input_value.value; var total_time = parseInt(minut ...

Guide on creating custom error messages for cross field validation in vee-validate

Take a look at this guide for more information. In the scenario presented here, I am looking to display the values of min and max in my message. Can you help me with that? https://i.sstatic.net/2mD7f.png ...

Recognizing the click event on the checkbox within a <TableRow/> in ReactJS with MaterialUI

Using ReactJS and MaterialUI's component for tables, I have successfully created a table with two rows, each containing a checkbox. Now, the challenge is to create a method that can recognize when a checkbox is clicked and provide information about th ...

RxJS - Only emit if another source does not emit within a specified time frame

Imagine having two observables. Whenever the first one emits, there should be a 2-second pause to check if the other observable emits something within that timeframe. If it does, then no emission should occur. However, if it doesn't emit anything, the ...

Using Javascript to dynamically retrieve accordion content from a dynamically generated ID

I am currently working on developing a more intricate accordion feature. The accordion will consist of 4 buttons (section 0-3) with unique content (lorem ipsum 0-3). Clicking on "section 0" should reveal "lorem ipsum 0", while clicking on "section 1" shoul ...

Creating a smooth transition effect on text length using Javascript and CSS: Fading the text as it

I have been searching everywhere for a solution to my issue, but I haven't found it yet. I keep coming across methods to fade text on and off on load, which is not what I need. My goal is to fade some text on the same line, and I have created a mockup ...

Tips for populating a textfield with data from a <select> dropdown using javascript

Is there a way to populate a textfield with data automatically based on information provided in the tab, utilizing JavaScript? Additionally, is it possible to prevent the filled data from being edited? The textfield should be able to dynamically fill data ...

Connect the v-model to a non-existent property (Array) in Vue JS

I am struggling with retrieving questions from the database and displaying them along with options on a webpage. Here is an example: <div v-for="(question,index) in questions"> <div class="interview__item-text ...

Fullcalendar will automatically schedule the ending time 10 minutes past the hour that I have chosen

I'm currently working on a booking platform that utilizes fullcalendar. However, I've encountered an issue where the start and end times being sent to the PHP (Laravel) file for database storage are consistently 10 minutes later than the time I a ...

Issue encountered while initializing session_start() in PHP REACTJS AXIOS

https://i.sstatic.net/bSelX.pngWhen attempting to log in to my web application, I encountered an issue where the session is not opening after entering the correct email and password. Strangely, there is no PHPSESSID present in the console > application. ...

Is TinyMCE creating unexpected <g> tags?

When I save content in the TinyMCE WYSIWYG editor, I notice that the HTML tag below keeps appearing throughout the text: <g class="gr_ gr_283 gr-alert gr_spell gr_run_anim gr_inline_cards ContextualSpelling ins-del multiReplace" id="283" data-gr-id="28 ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

Avoid modifying the style of JSX destructuring code in the WebStorm pre-commit process

My preferred choice is: https://i.sstatic.net/XFIiA.jpg Prior to reformatting: https://i.sstatic.net/IhIQA.jpg Post reformatting: https://i.sstatic.net/GN2U1.jpg What settings should I keep to maintain the code as it was prior? ...

Issue with HighCharts Series Data Points Not Being Added

I am currently facing a major challenge in dynamically changing data for highcharts based on date. To provide context for my project, it involves logging system data with timestamps. I have implemented a date and time picker to specify the start and end da ...

Ways to hide several dropdowns in reactjs upon clicking outside

When working with custom dropdowns and states in react.js, I encountered an issue. Applying the code provided in the link below to two dropdowns resulted in the second dropdown's value changing while the first dropdown's value remained unchanged. ...

Unexpected date outcomes in JavaScript when using a similar date format

Why is it that the first input produces the correct result, while the second input displays a time that is 5 hours behind? new Date("2000-1-1") Sat Jan 01 2000 00:00:00 GMT-0500 (EST) new Date("2000-01-01") Fri Dec 31 1999 19:00:00 GMT-0500 (EST) How can ...

Utilizing Selenium automation to navigate a website that features a custom jQuery plugin-checkbox functionality

Utilizing Selenium WebDriver along with JavaScript to automate the testing of a website that features a custom jquery plugin named "jcf" (JavaScript Custom Forms) for aesthetically pleasing forms. You can find more information about this plugin here. I am ...

Error encountered in VueJS 2: Uncaught ReferenceError: _ is not defined when using debounce

I'm attempting to implement a debounce function with a 500ms delay. I found guidance in the documentation provided here. methods: { // Retrieve necessary data for the page fetchData: _.debounce(function () { this.$http. ...

Tips for changing the first letter to uppercase in a p5.js variable

I'm currently working on developing a weather forecasting website using the p5.js framework in JavaScript. One issue I am facing is that the API I am utilizing only provides weather descriptions in lowercase format, whereas I want them to be displayed ...