Yup is throw error when I have min and not required

Viewed 3155

I try 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 });
  });

codesandbox.io example

The name is empty in x object, But yup throw an error of min. Why? Which rule can be applied to solve this problem?

I need to validate for min only if I have any characters in x. How can I do so using yup functions?

2 Answers

Yup throws Error as exception. You cant see by console.log. If you want to see error msg on console. In your case you want to check only if there is some value of name. Otherwise do not check run valudator for that you need to use yup.lazy then add condition in it:

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

Here is code:

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: "" };

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


Here is the demo: https://codesandbox.io/s/yup-render-only-input-tyjyu

I have a ticket out with the makers of yup to see if there is a way to do this with the built-in functionality. As a workaround, you can use a regular expression to accomplish this with the match function.

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

Here's the sandbox: https://codesandbox.io/s/hopeful-lewin-z77pc

Related