StefanTerdell / json-schema-to-zod

ISC License
322 stars 46 forks source link

add missing IP addresses string validations #71

Closed geko1971 closed 11 months ago

geko1971 commented 12 months ago

Hello Stefan, first of all congrats for your really helpful lib!

It would be great to add the missing string format validations that are part of JSON format assertion vocabulary, maybe starting from the ones that maps easily with zod assertions, such as IP Addresses validations.

That could only require a small change to src/parsers/parseString.ts module:

import { JSONSchema7 } from "json-schema";

export const parseString = (schema: JSONSchema7 & { type: "string" }) => {
  let r = "z.string()";
  if (schema.pattern)
    r += `.regex(new RegExp(${JSON.stringify(schema.pattern)}))`;
  if (schema.format === "email") r += ".email()";
+  if (schema.format === "ip") r += ".ip()";
+  if (schema.format === "ipv4") r += ".ip({ version: "v4" })";
+  if (schema.format === "ipv6") r += ".ip({ version: "v6" })";
  else if (schema.format === "uri") r += ".url()";
  else if (schema.format === "uuid") r += ".uuid()";
  else if (schema.format === "date-time") r += ".datetime()";
  if (typeof schema.minLength === "number") r += `.min(${schema.minLength})`;
  if (typeof schema.maxLength === "number") r += `.max(${schema.maxLength})`;
  return r;
};

Thank you!

grmkris commented 11 months ago

hello i'd like to achieve the same for date fields

"birthday": {
                  "title": "Birthday",
                  "type": "string",
                  "format": "date"
                },
StefanTerdell commented 11 months ago

@grmkris Date and time formats have no equivalents in Zod, sorry

grmkris commented 11 months ago

we could do z.coerce.date() ?

eriktim commented 5 months ago

@grmkris Date and time formats have no equivalents in Zod, sorry

They actually got added recently: https://github.com/colinhacks/zod/pull/1766