Search code examples
javascripttypescriptzod

How can I remove all whitespace in Zod?


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?


Solution

  • 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' }))