Tips for validating numeric fields that rely on each other with Yup

I am facing a challenge in setting up a complex validation using the library yup for a model with interdependent numeric fields.

To illustrate, consider an object structured like this:

{
    a: number,
    b: number
}

The validation I aim to achieve is ensuring that b is less than half of a.

An ideal solution would look something like this conceptually:

yup.object().shape({
    a: yup
        .number(),
    b: yup
        .number()
        .max(a/2) <-- DOES NOT WORK

However, the issue arises as there is no reference to a within the scope.

Exploring the use of test, but struggling to incorporate the entire object into the scope:

yup.object().shape({
    a: yup
        .number(),
    b: yup
        .number()
        .test('test', 'b should be less than a/2', b => b < a/2) <-- DOES NOT WORK

Even considering when for conditional validation does not provide a solution, despite its potential for handling intricate validations of related fields:

yup.object().shape({
    a: yup
        .number(),
    b: yup
        .number()
        .when('a', {is: true, then: yup.number().max(a/2)}) <-- DOES NOT WORK

Answer №1

There appear to be additional variations of the when method that transfer the value of the field being tested:

yup.object().shape({
x: yup
    .date(),
y: yup
    .date()
    .when('x', (x, schema) => return schema.min(x))

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

In order to set a condition for the mat date picker to display a text box in Angular if the selected date is for someone under 18 years old

I need assistance with displaying a text field based on age validation. The requirement is to show the input field only if the age is less than 18. Below is the code snippet I am currently working with: <form [formGroup]="form"> ...

Deciphering intricate Type Script Type declarations

I am seeking clarification on how to utilize the object type for sending headers, aside from HttpHeaders provided in the HTTPClient declaration. While working with Angular HttpClient, I aim to include headers using an Object. However, I am unsure of how t ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

What could be causing my items to appear twice and as blank elements?

I'm feeling a bit lost here as to why my code isn't functioning correctly. For some reason, it's not displaying the predefined items that I've set up. Any guidance or assistance would be greatly appreciated. Dealing with Angular errors ...

Modifying data types within complex nested object structures

I am looking to traverse the data structure recursively and create a custom type with specific fields changed to a different type based on a condition. Using the example structure below, I aim to generate a type (Result) where all instances of A are repla ...

Rendering Information in Angular 4 Through Rest API

Encountering issues displaying data from my local express.js REST API, organized as follows: people: [{ surname: 'testsurname', name: 'testname', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Execute --runTestsByPath on two or more distinct paths

Currently, I am utilizing the jest cli for running my tests. Jest offers a useful cli option known as --runTestsByPath, which allows me to specify the locations of my tests. Despite having unit tests spread out in various directories within my repository, ...

Issue with e2e.js file format in Cypress Support

I am trying to save Cypress screenshots into a report using a support file as recommended in the documentation. However, I keep encountering an error: Your supportFile is missing or invalid: support/e2e.js The supportFile must be a .js, .ts, .coffee file ...

Encountered an issue during the migration process from AngularJS to Angular: This particular constructor is not compatible with Angular's Dependency

For days, I've been struggling to figure out why my browser console is showing this error. Here's the full stack trace: Unhandled Promise rejection: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependen ...

Struggling to bring in { useActionState } from 'react' while trying to follow the latest next.js tutorial with next.js v15.0.0-canary.28, react v19.0.0-rc, and types/react v18.2.21

Currently, I am following the tutorial on next.js available at https://nextjs.org/learn/dashboard-app I have reached chapter 14, which focuses on enhancing accessibility, located at https://nextjs.org/learn/dashboard-app/improving-accessibility During on ...

Guide on obtaining the total value from a JSON Array in Angular 2 using TypeScript

I received a JSON response which includes carts values with different amounts. "carts": { "value": [ { "Amt": 40 }, { "Amt": 20.25 }, ...

Using LitElement: What is the best way to call functions when the Template is defined as a const?

When the template is defined in a separate file, it's not possible to call a function in the component. However, if the template is defined directly as returning rendered HTML with this.func, it works. How can one call a function when the template is ...

"Ionic 3: Utilizing the If Statement within the subscribe() Function for Increased Results

I added an if conditional in my subscribe() function where I used return; to break if it meets the condition. However, instead of breaking the entire big function, it only breaks the subscribe() function and continues to execute the navCtrl.push line. How ...

What is the method for creating pipes that filter multiple columns?

My pipe is designed to work exclusively for the "name" column and not for the author anymore. transform(items: Book[], filter: Book): any { if (!items || !filter) { return items; } // Filter items array; keep items that match and retu ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

Is it possible to use non-numeric values as keys in a Typescript Map?

During a lesson: private items: Map<number, string> = new Map(); ... this.items[aNumber] = "hello"; Results in this error message: An element has an any type because the expression of type number cannot be used to index type Map<numbe ...

Adjusting the value of a mat-option depending on a condition in *ngIf

When working with my mat-option, I have two different sets of values to choose from: tempTime: TempOptions[] = [ { value: 100, viewValue: '100 points' }, { value: 200, viewValue: '200 points' } ]; tempTimesHighNumber: TempOpt ...

Managing the ERR_NAME_NOT_RESOLVED issue

Currently, I am facing a task related to the health check endpoint where I need to receive a response from the backend or encounter a net::ERR_NAME_NOT_RESOLVED error if we are outside of a specific network. When attempting to send a request to my endpoin ...