Search code examples
react-nativeeslinttypescript-eslintzod

Custom ESLint rule to ban z.string().url() from zod


Under the hood Zod's url() uses new URL() to check for validity. Sadly, the URL class is broken on React Native and accepts anything so I want to use other means of checking URL validity. How can I implement a no-restricted-syntax ESLint rule to ban .url() usage (using Typescript as well)?

Here's a broken attempt at this:

'no-restricted-syntax': [
  'error',
  {
    selector:
      "CallExpression[callee.name='z'][callee.object.callee.property.name='string'][callee.property.name='url']",
    message: "Do not use z.string().url(), RN's new URL() doesn't throw on invalid URL.",
  },
]

But this is not flagged z.string().url().


Solution

  • The following syntax rule seemed to work for me in the playground:

    'no-restricted-syntax': [
      'error',
      {
        selector: "CallExpression[callee.object.callee.object.name='z'][callee.object.callee.property.name='string'][callee.property.name='url']",
        message: "Do not use z.string().url(), RN's new URL() doesn't throw on invalid URL."
      }
    ]
    

    eslint playground

    That site also provides a really helpful AST explorer tool which I was able to use to match your specific call AST.