Indeed, verifying parent.parent access

Currently, I am utilizing the yup module to validate my form. My objective is to access the parent in order to test the value.

Below is my schema:


enabled: yup.boolean(),
contactDetail: yup.object().shape({
  phoneNumber1: yup.string().nullable(),
  phoneNumber2: yup.string().nullable(),
  email: yup.string().test('email', 'test', async function() {
    // code to test the enabled value here
  })
}),

Unfortunately, the when method allows access only on the same level and not on the parent level.

Does anyone have a solution or idea for this scenario?

Answer №1

I encountered a similar issue and successfully utilized this workaround.

Tip: Provide the entire form-data as a context to the schema and access any form value using

this.options.context

  const schema = yup.object().shape({
        enabled: yup.boolean(),
        contactDetail: yup.object().shape({
          phoneNumber1: yup.string().nullable(),
          phoneNumber2: yup.string().nullable(),
          email: yup.string().test('email', 'test', async function () {
            // this.options.context.enabled
           
          }),
        }),
      });

Utilizing Context

Without Formik

Include your Form data as a context during validation

 schema.validateSync(data, {context: form_data})

With Formik

Use validate instead of validationSchema

Pass your Form data as the 4th argument in validateYupSchema, representing context that can be accessed later in the schema.

Provide your schema as the 2nd argument in validateYupSchema.

    <Formik
      validate={(value) => {
        try {
          validateYupSchema(value, schema, true, value);
        } catch (err) {
          return yupToFormErrors(err); //for rendering validation errors
        }

        return {};
      }}

       onSubmit={} />

The following pertains to asynchronous validation with Formik.

    <Formik
      validate={async (value) => {
        try {
          await validateYupSchema(value, schema, false, value);
        } catch (err) {
          return yupToFormErrors(err); //for rendering validation errors
        }

        return {};
      }}

       onSubmit={} />

Answer №3

One way to incorporate testing into your code is by utilizing the test method found in the Yup library. This allows you to access details from the parent level within the test function, as shown in the example below.

amount: Yup.string().test('amount-test3', 'amount is required', function (value) {
                    const { description } = this.parent;
                    return !(!!description && !Number(value));
                  })

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

Adding a KendoColorPicker to a column in a Kendo Grid

When using AngularJS with a Kendo UI grid, I need to have a column that includes a colorPicker. Below is the code I have implemented: $scope.thingsOptions = { sortable: "true", scrollable: "true", toolbar: [{ name: "create", text: "Add Profile ...

Utilizing JSX interpolation for translation in React JS with i18next

I am trying to utilize a JSX object within the interpolation object of the i18next translate method. Here is an example code snippet along with its result: import React from "react"; import {useTranslation} from "react-i18next&qu ...

Leveraging Angular to retrieve images from Google Feed API

I'm currently working on developing an RSS reader and trying to integrate images from the Google Feed API. While I have successfully extracted the publishedDate and contentSnippet, I am facing difficulty in getting the image src. The code snippets bel ...

Error: The function stripHtml cannot be found

Currently, I am developing a blog website using Next Js. I encountered an issue while creating a rich text-editor API for the blog. When attempting to utilize string-strip-html, an error message was displayed as follows: C:\Users\alami\OneDr ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

The scripts within the body tag are failing to load

After trying to embed angular into the body tag, I noticed that nothing is loading up. Upon inspecting the resources panel, I found that only files from the head are present. Moving all the scripts to the head section resolves the issue and everything load ...

Triggering a modal window with unique content by clicking on various images

Is there a way to trigger a modal window through clicking on an image? Additionally, can different images open different content upon clicking? I am planning to showcase a portfolio where clicking on an image will activate a modal that displays other image ...

"Encountered a Parsing Error: function keyword was an unexpected token in an Async Function using a more recent version of Node

In the process of working on a side project, I am utilizing node and firebase technologies. While I have successfully created regular functions and cloud functions, I encountered an issue when attempting to create an async function like so: async function ...

What could be the reason for the list being undefined even though I explicitly defined it within the <script setup> section of my Nuxt 3 Project?

I am currently working on a Nuxt 3 Project and have created a component that generates a variable amount of elements. When calling the element, it is passed an array as a parameter. In the script setup, I define this array as 'list' and intend to ...

Enforce multiple npm modules to use a common dependency

Apologies for the beginner question, I am just starting out with npm and front end development. I have a library (A) that needs to be a singleton but requires initialization to pass start up configuration. Additionally, I have a library B which has libra ...

methods for sorting firestore data in react on client side

Fetching data from firestore and applying filters const [projects, setProjects] = useState([]); const fetchData = (sortBy = "NAME_ASC") => { const unsubscribe = firebase .firestore() .collection("projects") ...

Ways to modify the color of a container's border by interacting with radio buttons through JavaScript

I'm currently facing a challenge with creating a settings dropdown menu that allows users to select different themes. Each theme is supposed to modify the background color and border color, but I have successfully implemented only the background color ...

What is the best way to transfer the data from one JavaScript object to a new, empty object?

My Angular site requires a JavaScript object (JSON retrieved from a database) to display widgets: [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','wid ...

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...

Display loading icon in AngularJS during template retrieval

Imagine I have this specific directive: angular .module('app.widgets') .directive('myCalendarRange', myCalendarRange); function myCalendarRange () { var directive = { link: link, templateUrl: '/template/is/located ...

What is preventing ColladaLoader.js in Three.js from loading my file?

Recently, I decided to experiment with three.js and wanted to load a .dae file called Raptor.dae that I obtained from Ark Survival Evolved. Despite having some web development knowledge, I encountered an issue when trying to display this particular file in ...

`How can you adjust the language preferences for users in Meteor?`

My website is internationalized using the tap-i18n plugin. I am looking to allow users to switch between languages on the site. Currently, I have a file called client/setLanguage.js where I set the language on startup: getUserLanguage = function () { ...

Struggling to display the preloader animation while waiting for the render.com server to start up (using the free tier web service)

My choice for deploying dynamic websites is render.com and I am currently using their free tier. The issue with this free service is that Render spins down the web service after 15 minutes of inactivity, resulting in a delay when it needs to spin back up u ...

Creating an accordion feature within an ng-repeat using AngularJS based on user clicks

When I click on the span with ng-click="click_subcat(opp.ct_nm);, the content is loaded within the <span ng-click="click_pdms(opp.sbct_nm);" style="color:white;cursor:pointer">{{opp.sbct_nm}}</span>. The issue arises when I click on that span a ...

Submitting data using JavaScript's POST method

I am facing a challenge with posting Array data to an HTTP connector. My data is structured as follows: var data = [{ key:'myKey', keyName:'myKeyName', value:'value', valueName:'valueName' }, { ...