How validate e164 phone number with custom message in case field is empty? #6205
Replies: 2 comments 1 reply
|
Hi @evgeniyworkbel! I'm Dosu and I'm helping the Zod team. You can achieve this by chaining validators — they execute in the order they're defined, so the first failing check produces the error message the user sees. Zod 4 (recommended) has a built-in const phoneSchema = z
.string({ error: "Field is required" })
.min(1, "Field is required")
.e164("Field must be e164 format");The Zod 3 doesn't have const E164_REGEX = /^\+[1-9]\d{1,14}$/;
const phoneSchema = z
.string({ required_error: "Field is required" })
.min(1, "Field is required")
.regex(E164_REGEX, { message: "Field must be e164 format" });In both cases:
Note that Zod 3 uses Feel free to close this discussion if that answers your question! To reply, just mention @dosu. Share context across your team and agents. Try Dosu. |
|
Use a pipeline so the E.164 validator is only evaluated after the non-empty check succeeds: import { z } from "zod";
const phone = z
.string({
error: (issue) =>
issue.input === undefined || issue.input === null
? "Field is required"
: "Field must be a string",
})
.trim()
.min(1, { error: "Field is required" })
.pipe(z.e164({ error: "Field must be E.164 format" }));This gives the requested precedence: phone.safeParse("").error?.issues[0].message;
// "Field is required"
phone.safeParse(" ").error?.issues[0].message;
// "Field is required"
phone.safeParse("555-555-5555").error?.issues[0].message;
// "Field must be E.164 format"
phone.parse("+15555555555");
// "+15555555555"
The If this solves the validation order, please mark it as the accepted answer so future readers can find it easily. |
Uh oh!
There was an error while loading. Please reload this page.
I want to validate string with custom message in case field is empty. Checks must be in the following order:
All reactions