You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an Int or that a string is a valid email address.
194
193
195
194
For this instances, you can define custom a validation check on _any_ Zod schema with `.refine`:
196
195
197
196
```ts
198
-
const myString =z.string().refine(val=>val.length<=255, "String can't be more than 255 characters");
message: "String can't be more than 255 characters",
199
+
});
199
200
```
200
201
201
-
Here is the type signature for `.refine`:
202
-
203
202
As you can see, `.refine` takes two arguments.
204
203
205
204
1. The first is the validation function. This function takes one input (of type `T` — the inferred type of the schema) and returns `any`. Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.)
206
-
2. The second argument is a custom error message. Read more about error handling in Zod [here](#errors)
205
+
2. The second argument is a params object. You can use this to customize certain error-handling behavior:
206
+
207
+
```ts
208
+
typeRefineParams= {
209
+
// override error message
210
+
message?:string;
211
+
212
+
// override error path
213
+
path?: (string|number)[];
214
+
215
+
// params object you can use to customize message
216
+
// in error map
217
+
params?:object;
218
+
};
219
+
```
220
+
221
+
These params let you define powerful custom behavior. Zod is commonly used for form validation. If you want to verify that "password" and "confirmPassword" match, you can do so like this:
@@ -352,9 +399,9 @@ type Merged = z.infer<typeof merged>;
352
399
353
400
To "overwrite" existing keys, use `.extend` (documented below).
354
401
355
-
#### Augmentation
402
+
#### Extending objects
356
403
357
-
You can augment an object schema with the `.extend` method.
404
+
You can add additional fields an object schema with the `.extend` method.
358
405
359
406
> Before zod@1.8 this method was called `.augment`. The `augment` method is still available for backwards compatibility but it is deprecated and will be removed in a future release.
0 commit comments