10000 z.string().url() should reject invalid schemes like https://https://example.com · Issue #4406 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

z.string().url() should reject invalid schemes like https://https://example.com #4406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
HiroTonaka opened this issue May 19, 2025 · 0 comments

Comments

@HiroTonaka
Copy link

Currently, z.string().url() does not catch malformed URLs such as https://https://example.com.
These are technically invalid, but they still pass validation.

To work around this, I had to use a custom refine() with a URL parser and an additional scheme check.

Here's the custom validation I implemented:

const isValidUrl = (url: string): boolean => {
  const schemeMatches = url.match(/https?:\/\//g);
  if (schemeMatches && schemeMatches.length > 1) return false;

  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
};

const noticeUrlSchema = z
  .string()
  .trim()
  .refine(url => isValidUrl(url), {
    message: 'Invalid URL format',
  })
  .optional();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant
0