zod to check if string is only whitespaces

how do i use zod to check if a string is only whitespaces?
9 Replies
nexxel
nexxel2y ago
const inputSchema = z.object({
message: z
.string()
.min(1, { message: "Your message is empty!" })
.max(100, { message: "Your message must be less than 100 characters." }),
});
const inputSchema = z.object({
message: z
.string()
.min(1, { message: "Your message is empty!" })
.max(100, { message: "Your message must be less than 100 characters." }),
});
this is what i have so far but i also want to throw an error if its only spaces
John
John2y ago
I’m not sure what RegEx you need but Zod supports RegEx
Piotrek
Piotrek2y ago
Yeah, I would use some kind of regex for that Found something like that on stack /\A\s*\z/ It's only for whitespaces
Develliot
Develliot2y ago
It think it's .refine that allows you to check regex iirc = /^\s+$/ you probably want to trim strings though
nexxel
nexxel2y ago
there's a .regex too so trim the string and then check if its empty? thanks i;ll try this
CaptainStarz
CaptainStarz2y ago
You could also .preprocess strings and trim them and that would trigger min(1) rule if specific error message doesn’t matter
nexxel
nexxel2y ago
thanks works
Develliot
Develliot2y ago
Essentially remove all spaces at the beginning and end of the string to mitigate user error instead of validating against it. Usually its bad a11y to do magic like this when people are typing especially in the front end I feel this is OK to do and a bit more of a pleasant UX
nexxel
nexxel2y ago
noted thanks
Want results from more Discord servers?
Add your server