jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

`yup.string().required().optional()` thinks empty string is invalid. #2188

Open houkanshan opened 8 months ago

houkanshan commented 8 months ago

Describe the bug

Depends on the definition, it may not be a Bug.

string().required().optional() thinks empty string is invalid. Because undefined is valid in this case, treating empty string as invalid is strange.

I understand that string().defined().optional() and string().required().notRequired() are the correct usages. But I think it is still nice to make string().required().optional() to work properly.

Also, .partial() and .deepPartial() always call .optional() so object({ str: yup.string().required() }).partial() could also be an issue.

To Reproduce

https://stackblitz.com/edit/vitejs-vite-pwmcyx?file=main.js

import * as yup from 'yup';

const schema = yup.string().required().optional();
const result = {
  undefined: schema.isValidSync(), // valid
  '': schema.isValidSync(''), // invalid
  a: schema.isValidSync('a'), // valid
};
console.log(result);

Expected behavior

yup.string().required().optional().validate('') should be valid.

Platform (please complete the following information):