custom validation for q-checkbox

As the title suggests, I am facing an issue with custom validation on my q-checkbox. The standard Quasar validation method is not working for me.

Below are my checkboxes with custom DIVs for displaying error messages:

 <q-item style="padding-left: 0; padding-bottom: 0; margin-left: 0">
                      <q-checkbox
                          id="acceptedPrice"
                          v-model="acceptedPrice"
                          label='I have read and agree to the "Prices / Terms of Participation" category.'
                          style="padding-bottom: 0;"
                      />
                    </q-item>
                    <div v-if="showError"
                         style="padding: 8px 0 2px 16px; line-height: 1; min-height: 0;
                           color: #C10015; font-size: 13px;">
                      Please check the mandatory field.
                    </div>
                    <q-item style="padding-left: 0; padding-bottom: 0; margin-left: 0">
                      <q-checkbox
                          id="acceptedAgreement"
                          v-model="acceptedAgreement"
                          label='I have read and agree to the "Consent" category and consent to the use of my data.'
                          style="padding-bottom: 0;"
                      />
                    </q-item>

My TypeScript code:

const acceptedPrice = ref<boolean>(false);
const acceptedAgreement = ref<boolean>(false);
const showError = ref<boolean>(false);

async function onsubmit() {
  if (acceptedPrice.value !== true && acceptedAgreement.value !== true) {
    showError.value = true;
  }
  if (acceptedPrice.value === true && acceptedAgreement.value === true) {
    const success = await buildingBoomForm.value?.validate();
    if (success === true) {
      Notify.create({
        color: 'positive',
        icon: 'cloud_done',
        message: 'Form successfully submitted!'
      });
    }
  }
}

The error message now appears when the user forgets to check the boxes, but it does not react as I would like it to. It should disappear once the boxes are checked.

I tried using a computed property but couldn't get it to work properly. I also considered using watchers, but I don't think it's suitable for this case.

Answer №1

To resolve this issue, consider using the q-field

<q-field
  borderless
  :model-value="acceptedAgreement"
  lazy-rules
  :rules="[ val => !!val || 'This checkbox is required']"
>
  <q-checkbox
    v-model="acceptedAgreement"
    style="font-size: 0.85rem;"
    label="I agree to the terms and conditions *"
  />
</q-field>

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

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

How to load vector tiles from a binary file using OpenLayers

I'm attempting to load a vector tile in binary format into OpenLayers but I'm facing challenges with the tileLoadFunction. I'm struggling to manually set the data to the tile. The reason why I need to use the tileLoadFunction is because I ha ...

Having some issues with ng-hide in angular, it doesn't seem to be functioning properly

<nav class="menu-nav"> <ul> <li class="menu-li" ng-model="myVar"><a>Discover<i class="fa fa-chevron-down pull-right"></i></a> <div class="sub-menu" ng-hide="myVar"&g ...

Update of input not available

Does anyone know how to effectively transfer data from one page to another programmatically? I'm facing an issue where updating an input field doesn't work unless I manually edit it afterwards. Is there a better way to achieve this? Another prob ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

A TypeScript Class that Refers to Itself

I need help with representing a JSON object in an Angular2 typescript class. The JSON object contains an array of objects of its own type. Here is what the JSON object looks like: { "data": { "id": 5, "type": "taxons", "attributes": { ...

Tips for displaying just the image name without the entire image file path

When I try to upload an image, the path displayed is "C:\fakepath\promotion1.JPG". This fake path is causing the image not to upload to my project media folder. How can I solve this issue? Instead of the complete path, I only want to capture the ...

The value of the progress bar in Bootstrap Vue cannot be retrieved using a function

I have implemented a progress bar using Bootstrap Vue. Here is the HTML code: <b-progress :value="getOverallScore" :max=5 variant="primary" animated></b-progress> The getOverallScore function calculates an average value based on three differe ...

Generating a dynamic optional parameter for deduced generics

I have a specific object with the following structure: { first: (state: S, payload: boolean) => { payload: boolean, type: string }, second: (state: S) => { payload: undefined, type: string }, } My goal is to manipulate this object by removing th ...

Is it possible for namespaced modules to manage mutations in the root namespace?

Imagine this scenario: I have two namespaced modules: moduleA and moduleB. They both follow a similar structure: export default { namespaced: true, state: defaultState(), actions: { // ... }, mutations: { [SET_DATA] (state, data) { ...

What advantages do binary shifts offer in enums?

What do you think about this code snippet? /** * Bitmask of states */ export const enum ViewState { FirstCheck = 1 << 0, // result is 1 ChecksEnabled = 1 << 1, // result is 2 Errored = 1 << 2, // result is 4 ...

Utilizing the useContext hook within a strictly Typescript-based class component

I have developed a pure Typescript class that serves as a utility class for performing a specific task. Within this class, I have created a context that is intended to be used universally. My goal is to utilize this context and its values within the pure T ...

Issue with KeyboardDatePicker in Material-UI/Pickers occurs when InputAdornmentProps property with position start is added, leading to an unexpected margin

I am currently working with a component from material-ui/pickers and this is the code snippet: <KeyboardDatePicker value={selectedDate} onChange={(_, newValue) => handleClick(newValue)} labelFunc={renderLabel} disableToolbar variant=&a ...

Tips on verifying the existence of a file in Nuxt

Currently working with Nuxt version 2.15.4 and I am looking to verify within my store code whether a file exists in the Nuxt directory using the fs-extra package. It's straightforward when dealing with modules because I can obtain the file path utili ...

Guide on incorporating an SVG image into a vuetify text input field

Incorporating Vuetify into my project, I'm interested in enhancing the appearance of a text field by placing an SVG icon at the beginning. While I am aware that v-icon allows for icons to be prepended or appended, I prefer to use my own custom SVG ima ...

Creating a Next.JS Link that opens a new tab for internal URLs while avoiding redirection to external URLs

Currently, I am working on a project component for my homepage that showcases a specific project. The goal is to have the entire component redirect to the project page when clicked, except when the user clicks on the GitHub icon. In that scenario, I want t ...

What methods are available for utilizing a runtime variable that TypeScript is unaware of?

I am looking to implement a global variable in TypeScript that will be defined dynamically at runtime. This global variable is necessary for transferring configuration properties from the server-side language to JavaScript. My approach involves using TypeS ...

Utilizing a V-for/V-if loop to iterate through a multi-dimensional array and filter data based on date

I'm facing a challenge with setting up a v-for loop for an array I've constructed, which is already in the desired format Below is a snippet representing the data format. Essentially, I want to create a table for employees where the header consi ...

Tips for creating a string format for the value of an HTML attribute

I have set up a datalist with labels in the format: "City name (city code)" <!-- COG municipalities selector --> <input type="text" list="cogMunicipalities" [(ngModel)]="municipality" (click)="selectMunicipalityCode(municipality)"> <datalis ...