5

I am new to using zod for valiadtion. I have read through the documentation but I can see anything on how to add a validation for a phone number.

I used the email one to make sure a user enters a correct email, but how do I do the same for a phone number.

Currently it looks like this:

contactNumber: z
    .string()
    .min(10, { message: 'Must be a valid mobile number' })
    .max(14, { message: 'Must be a valid mobile number' }),

I am just not sure this is correct. I have made it a string because I want the user to be able to put a + in front of the number if necessary for example: +27823456787. I don't want the user to be able to put any letters in the number example: 072r536e98, If the user puts letters I want an error message to say "Must be a valid number".

Can anyone maybe advise me on the correct why to do the validation?

  • You cannot be advised if you don't specify what format you are requiring for a phone number. – possum Oct 25 '22 at 11:30
  • Phone numbers are incredibly more complex than emails. For one, emails are global, while phone numbers formats vary for each region. So first come up with your "correct" format, then we can think about validation. – Alejandro Oct 25 '22 at 12:19

2 Answers2

8

You could use a zod refinement to chain together a check from a library that is more capable of making that check. As was mentioned in the comments, the rules are complicated, and specific to the region.

There seems to be a validation from validator.js for example that could handle refining the string to a mobile phone number with isMobilePhone but you may want/need to have the user specify the country they are in.

An example of how this would work might be:

import { z } from "zod";
import validator from "validator";

const schema = z.object({
  name: z.string(),
  phone: z.string().refine(validator.isMobilePhone)
});

console.log(
  schema.safeParse({
    name: "test",
    phone: "+1-212-456-7890"
  })
); // Success

console.log(
  schema.safeParse({
    name: "test",
    phone: "2124567890"
  })
); // Success

console.log(
  schema.safeParse({
    name: "test",
    phone: "1234"
  })
); // Failure
Souperman
  • 5,057
  • 1
  • 14
  • 39
5

you can use regex, it worked for me =D.

const phoneRegex = new RegExp(
  /^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$/
);

const schema = z.object({
     phone: z.string().regex(phoneRegex, 'Invalid Number!'),
})