3

I was trying to chain multiple regex expressions for a single input field. Although it checked for every regex expression but only the error message for the first regex expression was being displayed on the screen. Is it even possible to chain regex expressions in Zod? If not what could be a good alternative solution to achieve the same result. Here is my code snippet:

export const Schema = z.object({
  fullname: z
    .string()
    .regex(new RegExp(/^[a-zA-Z]+[-'s]?[a-zA-Z ]+$/), 'Name should contain only alphabets')
    .regex(new RegExp(/^[a-zA-Z]+\s+[a-zA-Z]+$/), 'Please enter both firstname and lastname')
    .min(2, 'Name should have atleast 2 alphabets'),
});

"Name should contain only alphabets" -----> was displayed for every case

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Zerodha
  • 31
  • 1
  • 3

1 Answers1

1

I don't know if you can use multiple .regex specifiers, but you can add multiple .refine's.

export const Schema = z.object({
  fullname: z
    .string()
    .refine((value) => /^[a-zA-Z]+[-'s]?[a-zA-Z ]+$/.test(value), 'Name should contain only alphabets')
    .refine((value) => /^[a-zA-Z]+\s+[a-zA-Z]+$/.text(value), 'Please enter both firstname and lastname')
    .min(2, 'Name should have atleast 2 alphabets'),
});

If this doesn't work, check your regular expressions, you might've made them wrong for what you want them to do.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34