Where is Sanity's URL/email validation regex code located?

2 replies
Last updated: Sep 7, 2023
Can anyone point me to the exact code that validates things things like
"type": "url" | "email"
or for validations like
Rule.email()
(namely, the regex that's used)? I'm working on https://www.npmjs.com/package/@sanity-typed/zod and it would be cool to have it perform the exact same validations.
AI Update

I can help you find the validation code! The validation logic for Rule.email(), Rule.url(), and the type: 'email'/type: 'url' field types lives in the Sanity monorepo on GitHub.

The specific files you're looking for are in the @sanity/types package and the main sanity package:

For the Rule builder definitions:

For the actual validation implementation:

Based on the Sanity source code, here's what the validation does:

Email validation uses a relatively permissive regex pattern similar to:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/

This is intentionally simple - it's designed to catch obvious typos rather than enforce RFC-compliant email addresses.

URL validation doesn't use a regex at all. Instead, it leverages the native browser/Node.js URL constructor:

try {
  new URL(value)
  return true
} catch {
  return false
}

This is actually more robust than regex-based validation since it handles all the edge cases that URLs can have.

For your @sanity-typed/zod package, I'd recommend:

  1. Browse the stringValidator.ts file directly for the most current implementation
  2. For URL validation in Zod, consider using the same URL constructor approach rather than a regex - you could create a custom Zod refinement that wraps it
  3. The email regex is intentionally permissive, so matching it exactly should be straightforward

You might also want to check the validation type definitions to ensure you're covering all the validation rules that Sanity supports. The validation system is actively maintained, so keeping an eye on those files will help you stay in sync with any changes to the Sanity Rule.email regex validation code or other validation patterns.

Show original thread
2 replies

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?