According to the docs of Zod I can use trim, but trim will only remove the whitespace characters at the end and beginning. I am looking for a way to remove all of the whitespace characters. To give you an idea of the setup I am using (removed irrelevant code):
const stp = zodString({
invalid_type_error: '',
required_error: '',
}).trim()
.min(1, { message: '' })
.max(10, { message: '' })
.regex(reg, { message: '', });
Is there a way to implement some sort of trim to remove all white space with zodString?
According to the docs of Zod I can use trim, but trim will only remove the whitespace characters at the end and beginning. I am looking for a way to remove all of the whitespace characters. To give you an idea of the setup I am using (removed irrelevant code):
const stp = zodString({
invalid_type_error: '',
required_error: '',
}).trim()
.min(1, { message: '' })
.max(10, { message: '' })
.regex(reg, { message: '', });
Is there a way to implement some sort of trim to remove all white space with zodString?
Share Improve this question edited Sep 19, 2023 at 19:13 Darryl Noakes 2,7811 gold badge13 silver badges30 bronze badges asked Sep 19, 2023 at 13:18 I try so hard but I cry harderI try so hard but I cry harder 7051 gold badge8 silver badges20 bronze badges 6 | Show 1 more comment3 Answers
Reset to default 9Using a pipe, you can first remove the white spaces and then perform additional validations.
z.string().transform(value => value.replace(/\s+/g, ''))
.pipe(z.string().min(1, { message: 'This field is required' }))
zod supports the .trim()
transformation
docs
const mySchema = z.object({ mykey: z.string().trim() })
The method .trim()
you used in the code snippet will remove the whitespaces from both ends of the string.
If for some reason you want to filter all whitespaces use .transform()
z.string().transform(value => value.replaceAll(" ", ""))
z.string().regex(/^\S+$/);
– Mr. Polywhirl Commented Sep 19, 2023 at 13:23