Skip to content

Backslash not escaped correctly in regex in Zod validatorΒ #2733

@mchyll

Description

@mchyll

Description

I have a regex which disallows the backslash character in a query param. When generating Zod validators for this schema, the backslash character in the regex is not correctly escaped, and is instead applied to the next character in the regex (in my case, a forward slash), whereas the backslash character should itself be escaped with another backslash to behave like the original regex from the OpenAPI spec.

ESLint warns that this is violating their no-useless-escape rule, which is how I noticed this issue. It suggests two possible fixes:

  1. Remove the \. This maintains the current functionality.
  2. Replace the \ with \\ to include the actual backslash character. This is what I want

Reproducible example or configuration

openapi-ts.config.ts

import { defineConfig } from "@hey-api/openapi-ts";

export default defineConfig({
  input: "./openapi.json",
  output: {
    path: "./validators",
    clean: true,
  },
  plugins: ["zod"],
});

Outputted validators/zod.gen.ts

// This file is auto-generated by @hey-api/openapi-ts

import { z } from 'zod';

export const zCreateBackupData = z.object({
    body: z.optional(z.never()),
    path: z.optional(z.never()),
    query: z.object({
        backup_name: z.string().regex(/^[^.][^\/:*?"<>| ]*$/)
    })
});

/**
 * Success
 */
export const zCreateBackupResponse = z.void();

OpenAPI specification (optional)

{
  "openapi": "3.1.0",
  "info": {
    "title": "Zod regex issue",
    "version": "0.1.0"
  },
  "paths": {
    "/backup": {
      "post": {
        "operationId": "create_backup",
        "parameters": [
          {
            "name": "backup_name",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^[^.][^\\/:*?\"<>| ]*$"
            }
          }
        ],
        "responses": {
          "204": {
            "description": "Success"
          }
        }
      }
    }
  }
}

System information (optional)

  • @hey-api/openapi-ts: 0.85.0
  • eslint: 9.35.0

Metadata

Metadata

Assignees

Labels

bug πŸ”₯Something isn't workingjavascriptPull requests that update Javascript code

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions