How to fix “yup validation one of two fields required…”

When using Ractjs to develop a project, I got a problem “yup validation one of two fields required”, here is the solution to the error Yup validate either one of two fields is required…

Solutions to Yup validation one of two fields required

There are a few solutions to the Yup validation with two fields related errors.

Here are the ways that can solve the yup validation one of two fields related problems.

Solution 1:

If using when isn’t a strict requirement, I find this is a little easier to do using the test function as it’s more concise, easier to follow, and doesn’t require duplication of code or messages

const has = require('lodash/has');

validationSchema = {                                                                                         
            'email': Yup.string(),                                                                  
            'mobile': Yup.string(),
        'email or mobile',
        'email or mobile is required',
        (value) => has(value, 'email') || has(value, 'mobile')

Solution 2:

In fact, we can achieve it by creating a type that is interdependent on related_items_id and short_desc.

export interface BaseType {
    title: string;
    overview: string;

interface RelatedItemsType extends BaseType {
  related_items_id?: Array<any>;
  short_desc?: never;

interface ShortDescType extends BaseType {
  related_items_id?: never;
  short_desc?: string;

export type InitialValueType = RelatedItemsType | ShortDescType;

Then, you can make use of it:

const initialValues: InitialValueType = {
    title: "",
    overview: "",
    related_items_id: [],
    // short_desc: "" no longer required

Solution 3:

This is the way helped me fix the Yup validate either one of two fields is required error.

To check if at least one of them is completed.

const schema = yup.object().shape({
  'fieldOneName': Yup.string()
  .when('fieldTwoName', {
    is: (fieldTwo) => !fieldTwo || fieldTwo.length === 0,
    then: Yup.string()
      .required('At least one of the fields is required'),
  'fieldTwoName': Yup.string()
  .when(, {
    is: (fieldOne) => !fieldOne || fieldOne.length === 0,
    then: Yup.string().
      .required('At least one of the fields is required'),,
}, ['fieldOneName', 'fieldTwoName']) // <-- HERE!!!!!!!!