Check for string to not be empty?

Not sure why I am struggling with this right now:
const { gender, firstname, lastname, email, mobile } = recipientData;

if (
gender === undefined ||
gender === null ||
firstname === undefined ||
firstname === null ||
lastname === undefined ||
lastname === null ||
((email === undefined || email === null) &&
(mobile === undefined || mobile === null))
) {
throw new ResponseError("missing_data");
}
const { gender, firstname, lastname, email, mobile } = recipientData;

if (
gender === undefined ||
gender === null ||
firstname === undefined ||
firstname === null ||
lastname === undefined ||
lastname === null ||
((email === undefined || email === null) &&
(mobile === undefined || mobile === null))
) {
throw new ResponseError("missing_data");
}
Is there a better way of checking if the data is not set, unfortunatly I get the ResponseError if I pass empty strings.
5 Replies
Ebert
Ebert11mo ago
Hello, one way to improve your code is check for falsy values using the ! operator For example, instead of checking if theses values are null or undefined like this:
if (
gender === undefined ||
gender === null ||
firstname === undefined ||
firstname === null ||
lastname === undefined ||
lastname === null ||
)
if (
gender === undefined ||
gender === null ||
firstname === undefined ||
firstname === null ||
lastname === undefined ||
lastname === null ||
)
You can check if the value is falsy with the ! operator:
if (
!gender ||
!firstname ||
!lastname
)
if (
!gender ||
!firstname ||
!lastname
)
Have a quick look about checking for falsy values in Javascript on this article: https://www.freecodecamp.org/news/falsy-values-in-javascript/
freeCodeCamp.org
Falsy Values in JavaScript
Description A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined, null, NaN , 0, "" (empty string), and false of course. Checking for falsy values on variables It is possible to check for a falsy
Ebert
Ebert11mo ago
If you want to allow empty strings to pass on this verification you can use a logic like that:
if (
!gender && gender !== "" ||
!firstname && firstname !== ""||
!lastname && lastname !== ""
....
)
if (
!gender && gender !== "" ||
!firstname && firstname !== ""||
!lastname && lastname !== ""
....
)
Josh
Josh11mo ago
use a zod validator
Josh
Josh11mo ago
GitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
JUNGLEJIMBO
JUNGLEJIMBO11mo ago
big +1 for zod. colocating your types and validation feels like magic
Want results from more Discord servers?
Add your server