Indeed, validation under certain conditions

How can I validate an event using yup validatesync?

The input is an object that contains another object with 3 fields. The first field is required, and either field 2 or 3 should be present in the input, or use the default value.

In the code snippet below, the default value is not being used when the field is empty in the input.

For example: if field 2 is present, then field 3 is optional in the input but it should still use the default value from the schema.

obj = { "node": { "node1": { "field1": "value1", "field2": "value2", "field3": "value3" } } }

validate = () => yup.object({
    node1: yup.object({
      node2: yup.object().shape({
        field1: yup.string().required(),
        field2: yup.string().when('field3', {
          is: (field3: string) => field3.length === 0,
          then: yup.string().required(),
          otherwise: yup.string().default('my default1'),
        }),
        field3: yup.string().when('field2', {
          is: (field2: string) => !field2 || field2.length === 0,
          then: yup.string().required(message),
          otherwise: yup.string().default('my default2'),
        }),
      },
      [ [ 'field2', 'field3' ] ]
      ).required(),
    }),   })

Answer №1

Your code appears to be close to working correctly. After experimenting with different approaches, it seems that there are some issues with this behavior. However, I have managed to find a solution to your problem: Instead of using .length, avoid it as it may cause an error if the string is undefined. It's better to use !filedNUMBER throughout your code. Additionally, make sure to include default(...) for the required key as well. Your revised code will look something like this:

obj = { "node": { "node1": { "filed1": "value1", "filed2": "value2", "filed3": "value3" } } }

validate = () => yup.object({
    node1: yup.object({
      node2: yup.object().shape({
        filed1: yup.string().required(),
        filed2: yup.string().when('filed3', {
          is: (filed3: string) => !filed3,
          then: yup.string().required().default('my default1'),
          otherwise: yup.string().default('my default1'),
        }),
        filed3: yup.string().when('filed2', {
          is: (filed2: string) => !filed2,
          then: yup.string().required(message).default('my default2'),
          otherwise: yup.string().default('my default2'),
        }),
      },
      [ [ 'filed2', 'filed3' ] ]
      ).required(),
    }),   })

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

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...

Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful. Here is ...

Verifying with VueJS and Jest: How to test if a component's method calls an imported function

I've created a VueJS 2 component that has the following structure: <template> <div> <button @click="onFavorite"> Add to favorites </button> </div> </template> <script> import { tra ...

Move the remaining blocks after deletion

Is there a way to create a seamless effect when removing an element? I am looking to incorporate a transition or slide effect when deleting a block and causing the blocks below it to move up smoothly. const animateCSS = (element, animation, prefix = &ap ...

Updating a .txt file using JavaScript

Is there a method on the client side to add text to a file called text.txt using JavaScript? In Python: f = open("text.txt","w") f.write("Hello World") f.close() The code snippet above would input "Hello World" into the text file. I am looking for a sim ...

How can I personalize a Leaflet popup with image thumbnails and additional customization options?

I've been researching and trying out different solutions, but so far none of them have worked for me. My goal is to dynamically add a title, image, address, and name to popups on my leaflet map as data comes in. However, I'm experiencing some cha ...

Transmitting language codes from Wordpress Polylang to Angular applications

I am currently attempting to manage the language settings of my Angular application within WordPress using WordPress Polylang. To achieve this, I have set up the following structure in my Angular application: getLanguage.php <?php require_once(". ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

How to Insert JSON into React Component's Attribute?

I am struggling with setting the value of a React component using JSON in the attribute. I want to concatenate a letter or word, but it doesn't seem to work. Is there a correct way to combine strings within a Component's attribute? In this case, ...

Strange audio issues encountered in Internet Explorer 11

Incorporating HTML5 Audio into a website project for background playback during specific events is my current endeavor. An unusual occurrence has been identified with Internet Explorer failing to load audio from one of my web domains. To illustrate this i ...

Angular - enabling scroll position restoration for a singular route

Is there a way to turn off scroll restoration on a specific page? Let's say I have the following routes in my app-routing.module.ts file... const appRoutes: Routes = [{ path: 'home', component: myComponent}, { path: 'about', compon ...

One way to filter using a single array

Currently testing some angularJS with this particular example http://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_filter <ul> <li ng-repeat="x in names | filter : 'i'"> {{ x }} </li> </ul> Is ther ...

What is the best way to open a browser window at a quarter of its default size?

Is there a way to open a window at 25% of its default device browser window size? I attempted the code below, which worked. However, it only accepts pixel inputs and not relative % values. This makes it non-scalable across various devices. window.resizeT ...

Issue with Sliding Transition in React Material UI Drawer Component

I developed a custom drawer component for my React application const CustomSidebar = () => { return ( <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} > <Box> <Navigator / ...

The error message "TypeError: Cannot access 'url' property of undefined in Strapi

I am facing an issue with a list of items where some have download links while others do not. Whenever I try to render an undefined URL, it triggers an error. To resolve this, I attempted the following: if (spectacle.pdf.url) { const pdf = spectacle.p ...

Instructions on how to assign a class number to a div matching the cookie number

Cookie: $(document).ready(function(){ //hide all divs for the purpose of this example, you should have them hidden with your CSS //$('.picture.1').hide(); //check if the cookie is already set if ($.cookie("currentDiv") === ...

Find Discounts Array

Is there a way to determine the Array of Discounts based on the Base Price initially and then calculate them against the Amount After Discount? In the image provided below, we have the Base Price. This base price may include multiple discounts. Each disc ...

Angular 2 is not recognizing the element 'router-outlet'

I am currently utilizing universal-cli... This is how my app.node.module.ts appears: /** * This file and `main.browser.ts` are quite similar, for now! * By separating these, you can create logic, imports, etc that are "Platform" specific. * If you wis ...

Generate a random number using the Math.random() method in Node.js/JavaScript to access a folder on the local machine

I am facing a challenge in reading a JSON file located deep within multiple folders on my local machine. The issue arises because the folder name where the file is stored changes every time, as it is generated using the Math.random() method with the prefix ...

"Error: Variable becomes undefined due to the implementation of async-await in TypeScript

There has been a persistent issue I've been dealing with for some time now. The problem lies in the fact that vm_res is undefined within the async update_vm_raw_device function despite the function running smoothly. As a result, the value being update ...