Confirm that the array contains exactly 2 elements

Is there a way to confirm that an array contains exactly two specific values, for example:

['foo', 'bar']

After trying different approaches, the closest solution I found looks like this:

Yup.array()
  .of(Yup.mixed().oneOf(['foo', 'bar']))
  .min(2)
  .max(2)

However, this code snippet would also validate arrays like ['foo', 'foo'] and ['bar', 'bar']

Answer №1

To achieve this functionality, you have the option of utilizing the Yup test function. This function allows you to manipulate the current field value as well as other form field values. In the following example, we are checking if the field value contains duplicates such as ['foo', 'foo'], and then verifying that there are no duplicates and that every value in the field array includes either foo or bar:

Yup.array()
  .test('contains', 'Error message here', function (value) {
      let hasDuplicate = value.some((val, i) => value.indexOf(val) !== i);
      return !hasDuplicate && value.every(el => ['foo', 'bar'].includes(el));
   })
  .min(2)
  .max(2)

For more information on the test function, you can refer to: https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema

Answer №2

If you need a solution, you can create a function to handle this. It seems like you're specifically searching for 2 variables within an array. Here's my approach:

function checkArray(arr, first, second){
    let found = false;
    if(arr.includes(first) && arr.includes(second)){
        found = true;
    }
    return found;
}

checkArray(["apple", "orange"], "apple", "orange");

If your requirement is for an array with the exact same length, you can include a length check in the function as well. The updated function would look like this:

function checkArray(arr, first, second){
    let found = false;
    if(arr.length != 2) {
        return false;
    }
    if(arr.includes(first) && arr.includes(second)){
        found = true;
    }
    return found;
}

checkArray(["apple", "orange"], "apple", "orange");

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

Middleware that handles form post requests quickly became overwhelmed and resulted in a RangeError

Currently, I am working with a form using ejs templates to collect data. When accessing the "/" route, my application renders the "main" view and utilizes a middleware to handle the form data. However, I encountered an error stating "RangeError: Maximum ca ...

Remove an item from the options list in the select2 plugin after an event occurs

I am currently using the Select2 plugin in my project and I am facing an issue where I want to remove an option from the main list. However, when I click on the "x" button generated by the code, it only removes it temporarily from the plugin's list. U ...

Combining arrays in Javascript that share the same key by utilizing a loop

Can you advise on the most effective method to restructure an array for desired output? My goal is to combine all key values, whether in arrays or not, into objects with the same name key. Here is my current array: brands: [ 0:ZARA: {product: "ZARA Blac ...

Efficient techniques for converting a list to a set in Python 2.7

Currently in my code, I am utilizing the following: im_set=set(map(tuple, im_list[0])) to convert a list into a set. However, this process is significantly slow. Are there any alternative methods without using map that can expedite this conversion? Here ...

Transfer information using beforeEnter to navigate through route components

How can I pass data from a function called with beforeEnter to the corresponding route component(s)? The goal of using beforeEnter in this scenario is to validate the presence of a valid bearer token as a cookie. Currently, my beforeEnter function intera ...

Mastering the art of integrating a multi-step form in React

While developing a multi-step form in my React 17.0.1 application using Typescript version 4.1.2, I came across this helpful guide: https://dev.to/sametweb/how-to-create-multi-step-forms-in-react-3km4 The guide was clear up to step 6, which I decided to s ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

It is imperative that the 'Access-Control-Allow-Origin' header value in the response is not set to '*' when the request's credentials mode is 'include'

I am currently working on establishing a connection using socket.io between Angular and a Node.js Server Within Angular, I have set up a new socket by importing socket.io-client and connecting it as follows: import * as io from 'socket.io-client& ...

Make sure the page preloader is visible before any other content is loaded

Currently, I am working on a straightforward preloader page that remains visible until the main content of the page is completely loaded. Despite the functionality of the loading page, my main concern lies in the quick display of the main content before th ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

The PHP-generated table is not being appended to the specified div with jQuery

I am currently working on developing a webpage that displays live forex rates to users. I am pulling the values from a feed and echoing them into a table. My goal now is to use jQuery to show this table to the user. The issue I am facing is that when I tr ...

What is the best way to call another "put" action method within the same controller file?

My project revolves around the interaction of two models - User and Request. A User can create a food delivery Request, attaching tokens as rewards. Another User can then help deliver the request and claim the tokens. Within the same controller.js file, I ...

What is the best way to incorporate a description box for each city on the svg map that appears when you hover your mouse over it?

I am looking to display detailed descriptions for each city in the same consistent location on my map. With multiple pieces of information to include for each city, I want to ensure that the description box is positioned at the bottom of the map. Can any ...

Connect to Node-Red websocket server

My server is running node-red with embedded functionality. I am attempting to set up a new websocket listener on the server, but when I run the code provided, the websockets in my node-red application stop functioning properly. const WebSocket = require(& ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Why is the output [[]] instead of [] after removing the last array like [["1"]] using .splice()?

let array=[["1"]]; array[0].splice(0,1); // array = [[]] Why am I unable to make the sub-array blank when removing the last element? I want array = [] instead of [[]] after removing the last element from a sub-array. Check it out here: http://jsbin.com/ ...

Utilize the setInterval method to repeatedly call the random function

Can someone assist me in setting a time interval of about 1 second for this function? function random_imglink(){ var myimages=new Array() //insert your desired random images below myimages[1]="/documents/templates/bilgiteknolojileri/standalo ...

Obtain the index by clicking on an element within an HTMLCollection

Within my HTML code, I have 9 <div> elements with the class ".square". I am looking to make these divs clickable in order to track how many times each one is clicked and store that information in an array. For example, if the fifth <div> is c ...

Setting up and Building Arrays of Objects in C++

When initializing an array of objects, do all the objects get constructed immediately or is construction required after initialization? To illustrate this scenario, consider the following: Suppose we have a class like this: class Object{ public: int ...