Necessitating the selection of at least one option only when another condition is met

Struggling to figure out this validation schema using Yup for the first time. Essentially, I need to ensure that if hasCategory is set to true, at least one category must be selected. Currently, my schema looks like this:

const validationSchema = Yup.object()
.shape({
  hasCategory: Yup.boolean().required('Yes or No must be selected for special ad category'),
  cat1: Yup.boolean(),
  cat2: Yup.boolean(),
  cat3: Yup.boolean(),
  cat4: Yup.boolean(),
});

Therefore, if hasCategory is true, then either cat1, cat2, cat3, or cat4 must also be true. However, if hasCategory is false, none of those categories should be true.

Any help in guiding me towards the right solution would be greatly appreciated!

Answer №1

Here's a solution that should work

Yup.object()
  .shape({
    hasCategory: Yup.boolean().required(
      "Please select Yes or No for special ad category"
    ),
    cat1: Yup.boolean(),
    cat2: Yup.boolean(),
    cat3: Yup.boolean(),
    cat4: Yup.boolean()
  })
  .test("hasCategory", "At least one category must be set to true", (value)=>{
    // if hasCategory is false, the test passes 
    if(!value.hasCategory) return true;
    // the test passes if at least one of the categories is true, otherwise it fails
    return value.cat1|value.cat2|value.cat3|value.cat4
  })

Answer №2

Conditional validations can be easily implemented using the test() method provided by Yup.

const validationSchema = Yup.object().shape({
  hasCategory: Yup.boolean().required('Please select Yes or No for special ad category'),
  cat1: Yup.boolean(),
  cat2: Yup.boolean(),
  cat3: Yup.boolean(),
  cat4: Yup.boolean(),
}).test('hasCategory', 'At least one category must be selected', function(value) {
  if (this.parent.hasCategory) {
    return this.parent.cat1 || this.parent.cat2 || this.parent.cat3 || this.parent.cat4;
  } else {
    return true;
  }
});

Explanation

The test() method retrieves the value of the schema and allows access to the parent object for field manipulation. It returns true for a successful validation and false for a failed validation. When hasCategory is true, it ensures that at least one other category is also selected. If hasCategory is false, the validation passes automatically.

Answer №3

Instead of using individual properties like cat1, cat2, etc., consider utilizing an array called catArray.

const validationSchema = Yup.object()
.shape({
  hasCategory: Yup.boolean().required('Yes or No must be selected for special ad category'),
  catArray: Yup.array().when('hasCategory', 
  {
     is: true,
     then: Yup.array().min(1, 'One field must be checked'), 
  })
});

This approach could prove to be beneficial.

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

How can I add a character at a precise location while keeping the existing tags intact

Latest Update After further testing, it seems that the code performs well with a faux spacer, but runs into issues with the regex. The following scenarios work correctly: Selecting words above or below the a tag Selecting just one line directly above or ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

What is the best way to correlate two arrays of strings with one another?

I am working with two sets of data: First Set: let training = [ "Z1,1545 John Doe,P1", "Z2,2415 Shane Yu,P2" ]; Second Set: let skill = [ "P1, Shooting", "P2, Passing", ]; I need to combine both arrays bas ...

Utilize middleware nesting in Express.js

I am interested in implementing middleware to validate requests based on a RAML file. Below is an outline of my current code: // dependencies let resources = require('osprey-resources'); let errorHandler = require('request-error-handler&apo ...

Compiling TypeScript into JavaScript with AngularJS 2.0

Exploring the capabilities of AngularJS 2.0 in my own version of Reddit, I've put together a script called app.ts ///<reference path="typings/angular2/angular2.d.ts" /> import { Component, View, bootstrap, } from "angular2/angular2 ...

Customizing the appearance of several elements in CKEditor by applying inline styles

I am looking to apply inline styling to multiple HTML elements using the CKEditor's inline style option. In order to achieve this, I have included the following code snippet in the styles.js file: { name: 'Red italics', element: 'p&apo ...

Using fancybox to send an ajax post request to an iframe

Can you send a variable to the iframe when using fancybox? This is my current setup: function fancyBoxLoad(element) { var elementToEdit = $("#" + $(element).attr("class")); var content = encodeURIComponent($(elementToEdit).oute ...

Creating dynamic SQL queries for bulk inserting data into Postgres using Vercel

Can anyone help me with creating an SQL bulk insert query using the sql helper from @vercel/postgres? I have a array of objects with different property types (number, string, date) and need to dynamically build the query. Simply creating a string and passi ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

Success function in Classic ASP with Ajax Form isn't functioning properly, but the complete function is working fine

When using Ajax and JS/Jquery, I am attempting to send a basic Contact form to a Classic ASP (aspemail) without reloading the page. <form id="form-submit" action="ASPEmail.asp" method="post"> Name<br> <input id="name" type="text"&g ...

In JavaScript, learn how to trigger a statement only when two specific events occur simultaneously

<html> <head> <style> div{ border: 1px solid black; width: 500px; height: 500px; } </style> <script> window.onload = function(){ document.body.onmousedown = function ...

Duplicate request submissions in ExtJs causing inefficiency

Trying to resolve an issue with my ExtJs table that handles remote filtering, sorting, and paging of data on the server. The problem arises when a default request is being sent alongside every other request: localhost/request?page=1&start=0&limit= ...

(basic) Issue with Jquery ajax request not receiving data

The alert box is not displaying anything and is not returning any data from the specified URL, even though it should show the Google page! Any suggestions? I am using the POST method because I need to send querystring data as well. $.ajax({ ...

Python's Selenium Throws No Such Element Exception

Looking to automate tasks involving hyperlinks on my university's SAP Portal, I decided to use Selenium. However, encountering difficulties as many web elements are dynamically generated using JavaScript, making them invisible to the webdriver. The e ...

Using JavaScript/jQuery to analyze POST values just before submission

Currently facing a dilemma as my company is in the process of redesigning its website. I find myself stuck trying to come up with a temporary fix for an issue on the existing site. The solution requires the use of JavaScript or jQuery. The problem arises ...

Creating a "briefing" iframe at the top of a webpage

I'm looking for a way to allow users to embed my iframe at a specific size, like 100x100, and then have it resize dynamically to fit the page size when they click on it. I want this functionality to work regardless of how the HTML embedding the iframe ...

When configuring Webpack with a rule array, JSX is not properly recognized by the tool

Here is the configuration for my webpack setup: const path = require('path'); module.exports = { entry: './src/entry.jsx', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist&ap ...

Dynamic jQuery Carousel

Is there a jQuery slider that can adapt to different screen sizes and handle images of varying widths? Appreciate any insights! ...

The Cordova minification tool fails to compress files within the browser platform

I recently installed the cordova-minify plugin to compress the javascript code in my Cordova app. When I tried running the command: cordova build browser An output message appears: cordova-minify STARTING - minifying your js, css, html, and images. ...

Having trouble with Angular minification not properly updating templates?

As a newcomer to angular development, I am currently working on creating components for AEM 6.2 using angular and utilizing gulp to minify the js files for all the components. In my gulpfile, I have set up the following configuration: var uglify = require ...