8000 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
Closed
@HiroTonaka

Description

@HiroTonaka

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();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0