Skip to content

Instantly share code, notes, and snippets.

@luanlmd
Created July 23, 2025 14:43
Show Gist options
  • Save luanlmd/8305f095f0f11358d3c713f6f003a9a9 to your computer and use it in GitHub Desktop.
Save luanlmd/8305f095f0f11358d3c713f6f003a9a9 to your computer and use it in GitHub Desktop.
import { z } from 'zod';
declare module 'zod' {
interface ZodString {
ip({ message }?: { message: string }): ZodString;
}
}
// Add the ip() method to ZodString prototype
z.ZodString.prototype.ip = function ({ message }: { message: string } = { message: 'Invalid IP address' }) {
return this.refine((val: string) => {
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
return ipv4Regex.test(val) || ipv6Regex.test(val);
}, message);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment