Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

add .includes(value, options?) @ ZodString. #1887

Merged
merged 8 commits into from Mar 5, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -584,6 +584,7 @@ z.string().url();
z.string().uuid();
z.string().cuid();
z.string().regex(regex);
z.string().includes(string);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().trim(); // trim whitespace
Expand All @@ -610,6 +611,7 @@ z.string().length(5, { message: "Must be exactly 5 characters long" });
z.string().email({ message: "Invalid email address" });
z.string().url({ message: "Invalid url" });
z.string().uuid({ message: "Invalid UUID" });
z.string().includes("tuna", { message: "Must include tuna" });
z.string().startsWith("https://", { message: "Must provide secure URL" });
z.string().endsWith(".com", { message: "Only .com domains allowed" });
z.string().datetime({ message: "Invalid datetime string! Must be UTC." });
Expand Down
140 changes: 86 additions & 54 deletions deno/lib/README.md
Expand Up @@ -52,6 +52,7 @@
- [Deno](#from-denolandx-deno)
- [Basic usage](#basic-usage)
- [Primitives](#primitives)
- [Coercion for primitives](#coercion-for-primitives)
- [Literals](#literals)
- [Strings](#strings)
- [Numbers](#numbers)
Expand Down Expand Up @@ -361,6 +362,7 @@ There are a growing number of tools that are built atop or support Zod natively!
- [`zod-formik-adapter`](https://github.com/robertLichtnow/zod-formik-adapter): A community-maintained Formik adapter for Zod.
- [`react-zorm`](https://github.com/esamattis/react-zorm): Standalone `<form>` generation and validation for React using Zod.
- [`zodix`](https://github.com/rileytomasek/zodix): Zod utilities for FormData and URLSearchParams in Remix loaders and actions.
- [`remix-params-helper`](https://github.com/kiliman/remix-params-helper): Simplify integration of Zod with standard URLSearchParams and FormData for Remix apps.
- [`formik-validator-zod`](https://github.com/glazy/formik-validator-zod): Formik-compliant validator library that simplifies using Zod with Formik.
- [`zod-i18n-map`](https://github.com/aiji42/zod-i18n): Useful for translating Zod error messages.
- [`@modular-forms/solid`](https://github.com/fabian-hiller/modular-forms): Modular form library for SolidJS that supports Zod for validation.
Expand Down Expand Up @@ -507,8 +509,53 @@ z.unknown();
z.never();
```

## Coercion for primitives

Zod now provides a more convenient way to coerce primitive values.

```ts
const schema = z.coerce.string();
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"
schema.parse(true); // => "true"
```

During the parsing step, the input is passed through the `String()` function, which is a JavaScript built-in for coercing data into strings. Note that the returned schema is a `ZodString` instance so you can use all string methods.

```ts
z.coerce.string().email().min(5);
```

All primitive types support coercion.

```ts
z.coerce.string(); // String(input)
z.coerce.number(); // Number(input)
z.coerce.boolean(); // Boolean(input)
z.coerce.bigint(); // BigInt(input)
z.coerce.date(); // new Date(input)
```

**Boolean coercion**

Zod's boolean coercion is very simple! It passes the value into the `Boolean(value)` function, that's it. Any truthy value will resolve to `true`, any falsy value will resolve to `false`.

```ts
z.coerce.boolean().parse("tuna"); // => true
z.coerce.boolean().parse("true"); // => true
z.coerce.boolean().parse("false"); // => true
z.coerce.boolean().parse(1); // => true
z.coerce.boolean().parse([]); // => true

z.coerce.boolean().parse(0); // => false
z.coerce.boolean().parse(undefined); // => false
z.coerce.boolean().parse(null); // => false
```

## Literals

Literals are zod's equivilant to [TypeScript's Literal Types](https://www.typescriptlang.org/docs/handbook/literal-types.html) which alow only the exact given type and value.

```ts
const tuna = z.literal("tuna");
const twelve = z.literal(12);
Expand Down Expand Up @@ -537,6 +584,7 @@ z.string().url();
z.string().uuid();
z.string().cuid();
z.string().regex(regex);
z.string().includes(string);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().trim(); // trim whitespace
Expand All @@ -563,54 +611,12 @@ z.string().length(5, { message: "Must be exactly 5 characters long" });
z.string().email({ message: "Invalid email address" });
z.string().url({ message: "Invalid url" });
z.string().uuid({ message: "Invalid UUID" });
z.string().includes("tuna", { message: "Must include tuna" });
z.string().startsWith("https://", { message: "Must provide secure URL" });
z.string().endsWith(".com", { message: "Only .com domains allowed" });
z.string().datetime({ message: "Invalid datetime string! Must be UTC." });
```

## Coercion for primitives

Zod now provides a more convenient way to coerce primitive values.

```ts
const schema = z.coerce.string();
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"
schema.parse(true); // => "true"
```

During the parsing step, the input is passed through the `String()` function, which is a JavaScript built-in for coercing data into strings. Note that the returned schema is a `ZodString` instance so you can use all string methods.

```ts
z.coerce.string().email().min(5);
```

All primitive types support coercion.

```ts
z.coerce.string(); // String(input)
z.coerce.number(); // Number(input)
z.coerce.boolean(); // Boolean(input)
z.coerce.bigint(); // BigInt(input)
z.coerce.date(); // new Date(input)
```

**Boolean coercion**

Zod's boolean coercion is very simple! It passes the value into the `Boolean(value)` function, that's it. Any truthy value will resolve to `true`, any falsy value will resolve to `false`.

```ts
z.coerce.boolean().parse("tuna"); // => true
z.coerce.boolean().parse("true"); // => true
z.coerce.boolean().parse("false"); // => true
z.coerce.boolean().parse(1); // => true
z.coerce.boolean().parse([]); // => true

z.coerce.boolean().parse(0); // => false
z.coerce.boolean().parse(undefined); // => false
z.coerce.boolean().parse(null); // => false
```

### Datetime validation

The `z.string().datetime()` method defaults to UTC validation: no timezone offsets with arbitrary sub-second decimal precision.
Expand Down Expand Up @@ -729,21 +735,28 @@ z.date().min(new Date("1900-01-01"), { message: "Too old" });
z.date().max(new Date(), { message: "Too young!" });
```

**Supporting date strings**
**Coercion to Date**

To write a schema that accepts either a `Date` or a date string, use [`z.preprocess`](#preprocess).
Since [zod 3.20](https://github.com/colinhacks/zod/releases/tag/v3.20), use [`z.coerce.date()`](#coercion-for-primitives) to pass the input through `new Date(input)`.

```ts
const dateSchema = z.preprocess((arg) => {
if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
}, z.date());
type DateSchema = z.infer<typeof dateSchema>;
const dateSchema = z.coerce.date()
type DateSchema = z.infer<typeof dateSchema>
// type DateSchema = Date

dateSchema.safeParse(new Date("1/12/22")); // success: true
dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true
/* valid dates */
console.log( dateSchema.safeParse( '2023-01-10T00:00:00.000Z' ).success ) // true
console.log( dateSchema.safeParse( '2023-01-10' ).success ) // true
console.log( dateSchema.safeParse( '1/10/23' ).success ) // true
console.log( dateSchema.safeParse( new Date( '1/10/23' ) ).success ) // true

/* invalid dates */
console.log( dateSchema.safeParse( '2023-13-10' ).success ) // false
console.log( dateSchema.safeParse( '0000-00-00' ).success ) // false
```

For older zod versions, use [`z.preprocess`](#preprocess) like [described in this thread](https://github.com/colinhacks/zod/discussions/879#discussioncomment-2036276).

## Zod enums

```ts
Expand Down Expand Up @@ -786,7 +799,7 @@ FishEnum.enum;
You can also retrieve the list of options as a tuple with the `.options` property:

```ts
FishEnum.options; // ["Salmon", "Tuna", "Trout"]);
FishEnum.options; // ["Salmon", "Tuna", "Trout"];
```

## Native enums
Expand Down Expand Up @@ -1270,12 +1283,31 @@ stringOrNumber.parse(14); // passes

Zod will test the input against each of the "options" in order and return the first value that validates successfully.

For convenience, you can also use the `.or` method:
For convenience, you can also use the [`.or` method](#or):

```ts
const stringOrNumber = z.string().or(z.number());
```

**Optional string validation:**

To validate an optional form input, you can union the desired string validation with an empty string [literal](#literals).

This example validates an input that is optional but needs to contain a [valid URL](#strings):

```ts
const optionalUrl = z.union( [
z.string().url().nullish(),
z.literal( '' ),
] )

console.log( optionalUrl.safeParse( undefined ).success ) // true
console.log( optionalUrl.safeParse( null ).success ) // true
console.log( optionalUrl.safeParse( '' ).success ) // true
console.log( optionalUrl.safeParse( 'https://zod.dev' ).success ) // true
console.log( optionalUrl.safeParse( 'not a valid url' ).success ) // false
```

## Discriminated unions

A discriminated union is a union of object schemas that all share a particular key.
Expand Down Expand Up @@ -2142,7 +2174,7 @@ z.promise(z.string());

### `.or`

A convenience method for union types.
A convenience method for [union types](#unions).

```ts
const stringOrNumber = z.string().or(z.number()); // string | number
Expand Down
1 change: 1 addition & 0 deletions deno/lib/ZodError.ts
Expand Up @@ -95,6 +95,7 @@ export type StringValidation =
| "regex"
| "cuid"
| "datetime"
| { includes: string; position?: number }
| { startsWith: string }
| { endsWith: string };

Expand Down
8 changes: 7 additions & 1 deletion deno/lib/__tests__/string.test.ts
Expand Up @@ -7,7 +7,9 @@ import * as z from "../index.ts";
const minFive = z.string().min(5, "min5");
const maxFive = z.string().max(5, "max5");
const justFive = z.string().length(5);
const nonempty = z.string().nonempty("nonempty");
const nonempty = z.string().min(1, "nonempty");
const includes = z.string().includes("includes");
const includesFromIndex2 = z.string().includes("includes", { position: 2 });
const startsWith = z.string().startsWith("startsWith");
const endsWith = z.string().endsWith("endsWith");

Expand All @@ -18,6 +20,8 @@ test("passing validations", () => {
maxFive.parse("1234");
nonempty.parse("1");
justFive.parse("12345");
includes.parse("XincludesXX");
includesFromIndex2.parse("XXXincludesXX");
startsWith.parse("startsWithX");
endsWith.parse("XendsWith");
});
Expand All @@ -28,6 +32,8 @@ test("failing validations", () => {
expect(() => nonempty.parse("")).toThrow();
expect(() => justFive.parse("1234")).toThrow();
expect(() => justFive.parse("123456")).toThrow();
expect(() => includes.parse("XincludeXX")).toThrow();
expect(() => includesFromIndex2.parse("XincludesXX")).toThrow();
expect(() => startsWith.parse("x")).toThrow();
expect(() => endsWith.parse("x")).toThrow();
});
Expand Down
8 changes: 7 additions & 1 deletion deno/lib/locales/en.ts
Expand Up @@ -47,7 +47,13 @@ const errorMap: ZodErrorMap = (issue, _ctx) => {
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("startsWith" in issue.validation) {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;

if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
Expand Down
20 changes: 20 additions & 0 deletions deno/lib/types.ts
Expand Up @@ -494,6 +494,7 @@ export type ZodStringCheck =
| { kind: "url"; message?: string }
| { kind: "uuid"; message?: string }
| { kind: "cuid"; message?: string }
| { kind: "includes"; value: string; position?: number; message?: string }
| { kind: "startsWith"; value: string; message?: string }
| { kind: "endsWith"; value: string; message?: string }
| { kind: "regex"; regex: RegExp; message?: string }
Expand Down Expand Up @@ -694,6 +695,16 @@ export class ZodString extends ZodType<string, ZodStringDef> {
}
} else if (check.kind === "trim") {
input.data = input.data.trim();
} else if (check.kind === "includes") {
if (!(input.data as string).includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: { includes: check.value, position: check.position },
message: check.message,
});
status.dirty();
}
} else if (check.kind === "startsWith") {
if (!(input.data as string).startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
Expand Down Expand Up @@ -798,6 +809,15 @@ export class ZodString extends ZodType<string, ZodStringDef> {
});
}

includes(value: string, options?: { message?: string; position?: number }) {
return this._addCheck({
kind: "includes",
value: value,
position: options?.position,
...errorUtil.errToObj(options?.message),
});
}

startsWith(value: string, message?: errorUtil.ErrMessage) {
return this._addCheck({
kind: "startsWith",
Expand Down
1 change: 1 addition & 0 deletions src/ZodError.ts
Expand Up @@ -95,6 +95,7 @@ export type StringValidation =
| "regex"
| "cuid"
| "datetime"
| { includes: string; position?: number }
| { startsWith: string }
| { endsWith: string };

Expand Down
8 changes: 7 additions & 1 deletion src/__tests__/string.test.ts
Expand Up @@ -6,7 +6,9 @@ import * as z from "../index";
const minFive = z.string().min(5, "min5");
const maxFive = z.string().max(5, "max5");
const justFive = z.string().length(5);
const nonempty = z.string().nonempty("nonempty");
const nonempty = z.string().min(1, "nonempty");
const includes = z.string().includes("includes");
const includesFromIndex2 = z.string().includes("includes", { position: 2 });
const startsWith = z.string().startsWith("startsWith");
const endsWith = z.string().endsWith("endsWith");

Expand All @@ -17,6 +19,8 @@ test("passing validations", () => {
maxFive.parse("1234");
nonempty.parse("1");
justFive.parse("12345");
includes.parse("XincludesXX");
includesFromIndex2.parse("XXXincludesXX");
startsWith.parse("startsWithX");
endsWith.parse("XendsWith");
});
Expand All @@ -27,6 +31,8 @@ test("failing validations", () => {
expect(() => nonempty.parse("")).toThrow();
expect(() => justFive.parse("1234")).toThrow();
expect(() => justFive.parse("123456")).toThrow();
expect(() => includes.parse("XincludeXX")).toThrow();
expect(() => includesFromIndex2.parse("XincludesXX")).toThrow();
expect(() => startsWith.parse("x")).toThrow();
expect(() => endsWith.parse("x")).toThrow();
});
Expand Down
8 changes: 7 additions & 1 deletion src/locales/en.ts
Expand Up @@ -47,7 +47,13 @@ const errorMap: ZodErrorMap = (issue, _ctx) => {
break;
case ZodIssueCode.invalid_string:
if (typeof issue.validation === "object") {
if ("startsWith" in issue.validation) {
if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;

if (typeof issue.validation.position === "number") {
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
}
} else if ("startsWith" in issue.validation) {
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
} else if ("endsWith" in issue.validation) {
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
Expand Down