Yup will throw an error if both a minimum value is set and the field is also marked

I am attempting to validate my schema using yup:

import * as yup from "yup";

let schema = yup.object().shape({
  name: yup.string().min(5)
});

const x = { name: "" };

// Check validity
schema
  .validate(x, { abortEarly: false })
  .then((result) => {
    console.log({ result });
  })
  .catch((err) => {
    console.log({ err });
  });

Example on codesandbox.io

The field name is empty in the object x, yet yup throws an error for min. Why is this happening? Is there a specific rule I can use to address this issue?

I want to apply the min validation only if there are any characters present in the x object. How can I achieve this using yup functions?

Answer №1

Indeed, it throws an Error as an exception. You cannot view it through a simple console.log. If you wish to see the error message on the console, in your scenario where you only want to check if there is some value for the name. Otherwise, skip running the validator. For this purpose, you can utilize yup.lazy and include a condition within it:

const mySchema = yup.lazy((value) =>
  yup.object().shape({
    name: value.name.length > 0 && yup.string().min(5) // add condition here
  })
);

Below is the code snippet:

import * as yup from "yup";

const mySchema = yup.lazy((value) =>
  yup.object().shape({
    name: value.name.length > 0 && yup.string().min(5)
  })
);

const x = { name: "" };

// validate
mySchema
  .validate(x, { abortEarly: false })
  .then((result) => {
    console.log({ result });
  })
  .catch((err) => {
    console.error(err);
    console.log("Error message", err.message);
  });


You can access the demo by visiting: https://codesandbox.io/s/yup-render-only-input-tyjyu

Answer №2

I reached out to the developers of yup for assistance on a particular issue and they have provided me with a ticket to address it. While waiting for their response, I found a temporary solution using regular expressions in combination with the match function.

let schema = yup.object().shape({
  name: yup.string().matches(/^(|.{5,})$/, "X must be at least 5 characters")
});

You can test this workaround in the sandbox here: https://codesandbox.io/s/hopeful-lewin-z77pc

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

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Displaying a React component within a StencilJS component and connecting the slot to props.children

Is there a way to embed an existing React component into a StencilJS component without the need for multiple wrapper elements and manual element manipulation? I have managed to make it work by using ReactDom.render inside the StencilJS componentDidRender ...

Creating a versatile function in TypeScript for performing the OR operation: A step-by-step guide

Is there a way in TypeScript to create a function that can perform an OR operation for any number of arguments passed? I currently have a function that works for 2 arguments. However, I need to make it work for any number of arguments. export const perfo ...

Is it possible to enhance an interface by integrating the characteristics of a constant?

I am currently working on customizing a material-ui v4 Theme. Within our separate @our-project/ui package, we have the following: export declare const themeOptions: { palette: { // some colors missing from Palette } status: string; // other pro ...

What is the reason that Ionic Lifecycle hooks (such as ionViewWillEnter and ionViewWillLeave) do not trigger when utilized as an HTML Selector?

I have a project using Angular along with Ionic 4. I encountered an issue where the Ionic Lifecycle Hooks in the child page do not fire when it is called from the parent page's HTML using the HTML Selector. Why does this happen? How can I properly ut ...

Exploring the MVVM architecture in React and the common warning about a missing dependency in the useEffect hook

I'm currently in the process of developing a React application using a View/ViewModel architecture. In this setup, the viewModel takes on the responsibility of fetching data and providing data along with getter functions to the View. export default f ...

What is the proper technique for utilizing private fields in TypeScript?

Every time I attempt to execute the code below that involves a private field, I encounter an "Invalid character" issue at the location of #. class MyClass { #x = 10; } Here is the content of my tsconfig.json file: { "compilerOptions": { ...

What is the best way to retrieve a specific field from the observable data stream?

When working with observables, I often find myself using them like this: ... const id = 1337; this.service.getThing(id).subscribe( suc => doSomething(suc.name), err = doSomethingElse() ); Lately, I've been utilizing the async pipe more freque ...

Troubleshooting an Integration Problem Between Express and socket.io

Having trouble reaching the io.on('connect') callback in my basic express setup. The connection seems to stall. Node 12.14.1 express 4.17.1 socket.io 3.0.1 code import express, { ErrorRequestHandler } from 'express'; import path from ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Differentiate the array type within an object in TypeScript

I understand how to specify the type for a variable. let members: string[] = [] // this example works flawlessly My goal is to have an array of strings within an object. How can I structure it correctly? const team = { name: String, members<st ...

The `findOne` operation in Mongoose fails to complete within the 10000ms time limit

Encountering this error on an intermittent basis can be really frustrating. I am currently using mongoose, express, and typescript to connect to a MongoDB Atlas database. The error message that keeps popping up reads as follows: Operation wallets.findOne() ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Utilizing TypeScript interfaces with additional parameter object members does not result in the anticipated compilation error

Consider the different types listed below: type Person = { id: string; name: string; }; interface PeopleRepository { getPerson(query: { id: string }): Person; } class Repository implements PeopleRepository { getPerson({ id, age }: { id: string; ...

Building Components on the Fly with Angular 5

I've been utilizing code similar to this to dynamically generate components within my application. These components need to support dynamic inputs. However, upon attempting to upgrade to Angular 5, I've encountered an issue with ReflectiveInjecto ...

Tips for simulating a Ref

I have a Vue3 component where, within the setup(), I have defined the following function: const writeNote(note: Ref<Note>) => { console.log(`note ${note.id}`) } This function takes a Ref<Note>, with Note being an Interface. There are two s ...

Swagger Issue Resolved: Restriction on Number of Params Set

After setting up this option for my route, I noticed that when accessing the first parameter (page), it correctly returns the value entered in Swagger UI. However, when trying to access the second parameter (genre), it seems to interpret it as a string &ap ...

Passing layout to a Vue component using the setup script

LayoutComponent <template> //some code here ... <div> <slot></slot> </div> </template> In the composition api, it is possible to pass a layout by importing it and then passing it into t ...

Tips for testing FormGroupDirective within a component

I am facing difficulties in testing a component with FormGroupDirective in the viewProviders section. I am unable to create a mock of the parent and set an empty formGroup. The component code is as follows: @Component({ (...) viewProviders: [ ...