How to parse an Ethereum address that was provided by a user with the help of zod safeParse() function?

2 Answers 2


From zod docs:

Zod lets you provide custom validation logic via refinements.

In order to achieve this you may want first to define a zod schema by using the refine() function in combination with ethers:

const ethAddressSchema = z.string()
    .refine((value) => ethers.utils.isAddress(value), {
        message: "Provided address is invalid. Please insure you have typed correctly.",

After that implement a basic validation:

const result = ethAddressSchema.safeParse("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");

You can also use custom in combination with isAddress from ethers (v5, v6).

import { isAddress } from 'ethers'; // ethers v6
import { z } from 'zod';

const Address = z.custom<string>(isAddress, "Invalid Address")

// Parse a value
Address.parse("abc"); // throws error

// Use in another Schema
const Token = z.object({ address: Address });
Token.parse({ address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" });
Token.parse({ address: "abc" }); // throws error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.