最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I remove all whitespace in Zod? - Stack Overflow

programmeradmin0浏览0评论

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
  • 2 "Trimming space" in the middle of a string is odd. Could you provide sample data demonstrating this? I can see compacting multiple spaces into one space. – Mr. Polywhirl Commented Sep 19, 2023 at 13:20
  • Well for example, you just wrote "Trimming space". I wish to have the white character in between "Trimming space" removed. – I try so hard but I cry harder Commented Sep 19, 2023 at 13:21
  • 1 Does this answer your question? Replace all whitespace characters – isherwood Commented Sep 19, 2023 at 13:21
  • 1 Wouldn't you just need z.string().regex(/^\S+$/); – Mr. Polywhirl Commented Sep 19, 2023 at 13:23
  • @isherwood No, because that would be done outside of the zodstring function. I am looking for a built-in way with zodString to resolve this. – I try so hard but I cry harder Commented Sep 19, 2023 at 13:24
 |  Show 1 more comment

3 Answers 3

Reset to default 9

Using 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(" ", ""))
发布评论

评论列表(0)

  1. 暂无评论