Determine if at least two out of the three checkboxes have been clicked using Vue JS

I am working on an Ant Design form that includes a model validation function with three checkboxes.

<a-form-model-item has-feedback label="CI/CD Stages" prop="stage">
   <a-checkbox-group v-model="form.stage">
     <a-checkbox value="1" name="stage"> Build Stage 1</a-checkbox>
     <a-checkbox value="2" name="stage"> Build Stage 2</a-checkbox>
     <a-checkbox value="3" name="stage"> Build Stage 3 </a-checkbox>
   </a-checkbox-group>
</a-form-model-item>

My goal is to have validation fail if both Build Stage 2 and Build Stage 3 are selected.

data() {
  ...
  let checkModuleStage = (rule, value, callback) => {
      clearTimeout(checkPending);
      checkPending = setTimeout(() => {
        if (value === [2, 3] || value === [3, 2]) {
          callback(
            new Error(
              "You have selected both Stage 2 and Stage 3. Only one can be selected:"
            )
          );
        } else {
          callback();
        }
      }, 1000);
}
return {
  rules: {
    stage: [
          {
            type: 'array',
            required: true,
            message: 'Please select at least one stage',
            trigger: 'change',
          },
          { validator: checkModuleStage, trigger: "change" },
        ],
  }
}

Despite implementing the validation function, I am still able to select both stages together. When I attempt to submit the form, it shows that the check passed. Does anyone have a solution for this issue? Thank you!

Answer №1

Make sure to update your conditional statement within the checkModuleStage function to:

if (value.some((x) => x === "2") && value.some((x) => x === "3"))

The reason why your current "if" statement is not functioning correctly:

  1. The values are stored as strings while you are expecting numbers.
  2. When comparing two arrays, looping through each array and comparing each value individually is necessary. Refer to this link for more information.

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

Calling JavaScript from iOS within a WebView can be easily achieved by following a few

I have a locally stored edge animation named index.html with 5 animated slides in an iOS app. I am loading this html in a UIWebView and looking for a way to send a message to the edge animation to display a specific slide in the WebView. How can I achieve ...

What is the best way to trigger a JavaScript function in an iframe from a child window within the main window?

In my main file, index.php, there is an iframe named main: <iframe src="main.php" id="main_frame" name="main_frame"> </iframe> The main.php file contains two iframes: middle_frame and top_frame. <iframe src="middle.php" id="middle_frame" ...

Refreshing forms in Angular 2

I am attempting to retrieve values from forms using the submit event. However, I am encountering difficulty resetting those forms later on. I am using an id called "myForm" and an onclick function to try and achieve this. <form (Submit)="addMarker()" i ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

What is the best way to toggle dropdown menu items using jQuery?

Upon clicking on an li, the dropdown menu associated with it slides down. If another adjacent li is clicked, its drop down menu will slide down while the previous one slides back up. However, if I click on the same li to open and close it, the drop down m ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...

Issue: GraphQL error: It is not possible to return null for the non-nullable field Mutation.updateRendezvous

While attempting to update a field, I encountered this error message: Error: GraphQL error: Cannot return null for non-nullable field Mutation.updateRendezvous. Below is the code snippet of my update function: updateApp() { this.submitted = true; ...

Determination of Vertical Position in a Displayed Table

I am trying to incorporate infinite scrolling with an AJAX-based loader in the body of an HTML table. Here is a snippet of my HTML code: <table> <thead> <tr><th>Column</th></tr> </thead> <tbody> ...

Javascript loop woes

I have a number array ranging from 1 to 20. My goal is to create a loop that extracts every nth element from the array, starting with (1, 6, 11, 16). After the initial loop, it should then extract every 5th element, starting from 2 (2, 7, 12, 17). My atte ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

Issue with AngularJS: Controller unable to access property of ng-model object

I am looking to create a reusable controller that can be used by multiple views. This controller will essentially serve as a template. The issue I'm facing is with setting up simple validation. The problem lies in the fact that the properties set in ...

Seamless integration of Applitools with WebdriverIO

Seeking assistance to integrate Applitools with my WebdriverIO project. Find the specifications below: Node Version: v12.18.2 NPM Version: 6.14.5 WebdriverIO Version: 6.3.6 The service in my wdio file is configured as follows: services: ['selenium-s ...

Using Jquery to activate a vertical scrolling bar

Within my div, I have a tree view that extends beyond the size of the div, causing a vertical scroll bar to appear on the right side. When users click a button outside of the div, I want the page to scroll to a specific item within the div (which I know th ...

How can I utilize JavaScript to generate a dynamic value in a URL and then submit it through a form?

One of my clients has requested the ability to send out unique URLs to their customers in order to track which links are being utilized. Despite my suggestion to use Google Analytics for this purpose, they have specifically asked to avoid it. Their reques ...

Adding an image to a jQuery class name on the fly

I am attempting to add an image before a div by using its className with jQuery. function insertImage(obj) { var dynamicClass = $(obj).prop("className"); After retrieving the classname, I now encapsulate it in single quotes and add a dot to access t ...

Encountering an EJS error stating SyntaxError: a closing parenthesis is missing after the argument list in the file path C:Userscomputer pointDesktopproject2viewshome.ejs

Struggling to retrieve data from app.js through ejs and encountering an error. Pursuing a degree in Computer Science <%- include('header'); -%> <h1><%= foo%></h1> <p class = "home-content">It is a fact that readers ...

Encountering an error with Sequelize while using Node.js Express with PostgresQL

Apologies for the extended and ambiguous title. I am facing a challenge when attempting to add a new user to my database through an HTTP request. While I have successfully created the necessary tables using my model files, I seem to encounter difficulties ...

Increase the row horizontally: Enlarge the row by several columns and dynamically load various components based on the selected column

I am currently working on implementing a feature called "expand row by column" using the example below. /* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; cons ...

Dealing with Sequelize Errors

After reviewing the code provided, I am curious if it would be sufficient to simply chain one .catch() onto the outermost sequelize task rather than attaching it to each individual task, which can create a cluttered appearance. Additionally, I am wonderin ...

Having trouble implementing highlighting functionality for a WebElement in Selenium with JavascriptExecutor on Firefox version 35

During the execution of a script designed to highlight and reset a WebElement in selenium 2.43: public void highlightElement(WebElement element) { String originalStyle = element.getAttribute("style"); JavascriptExecutor js = (JavascriptExecutor) sele ...