Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zod validation for phone numbers

Tags:

zod

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?

like image 714
Jennifer De Goede Avatar asked Sep 06 '25 03:09

Jennifer De Goede


2 Answers

April 2025

You can use z.e164() from Zod 4, based on the Phone Number E164 standard. Related PR


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
like image 79
Souperman Avatar answered Sep 07 '25 21:09

Souperman


You can use regex.

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

const schema = z.object({
     phone: z.string().regex(phoneRegex, 'Invalid Number!'),
})
like image 22
Christopher Lee Avatar answered Sep 07 '25 19:09

Christopher Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!