Number but allow empty string
See original GitHub issueI have a legacy project where a field can be a number, but the absence of value is defined by an empty string (instead of null
).
I am looking for something like nullable
(yup.number().allowEmptyString()
) or yup.mixed.oneOf(['', yup.number()]
Does anyone have an idea on how to handle this in the cleanest way?
Currently I am doing
const schema = yup
.mixed()
.test(fn) // value === '' || yup.number().isValidSync(value)
.transform(fn) // value === '' ? value : +value
but this loses beautiful syntax of Yup and just feels dirty since yup.number()
is burried inside test
, but may be further customized for other fields.
Thanks
Issue Analytics
- State:
- Created 5 years ago
- Reactions:12
- Comments:35 (4 by maintainers)
Top Results From Across the Web
How can I make a yup number accept nullable values?
However, when the field is left as empty, the value that it returns is NaN instead of null, so .nullable(true) is not working...
Read more >Reg exp allow empty strings or numbers only - MSDN - Microsoft
I have a reg exp that allows integers or decimals ^[1-9]\d{0,9}(\.\d{1,3})?%?$. How do I allow empty string (empty or null), integer or decimal?...
Read more >Test for Empty Strings and Missing Values - MATLAB & Simulink
Empty strings contain zero characters and display as double quotes with nothing between them ( "" ). You can determine if a string...
Read more >21.2 Validating Null and Empty Strings
An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null...
Read more >JavaScript Check Empty String – Checking Null or Empty in JS
There are a number of reasons why you might need to check if a string ... if we declare a variable and assign...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’m a little confused as to what the recommended solution is here.
I had a bit of hard times finding the right combination for my case (I don’t know why but I wasn’t able to make other solutions working in my code), so here is my working validation schema if it can help anybody: