Socket
Socket
Sign inDemoInstall

zod

Package Overview
Dependencies
Maintainers
1
Versions
361
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zod - npm Package Compare versions

Comparing version 1.8.0-beta.2 to 1.8.0-beta.3

4

lib/src/parser.d.ts

@@ -34,4 +34,6 @@ import * as z from './types/base';

declare type StripErrorKeys<T extends object> = T extends any ? util.OmitKeys<T, 'path'> : never;
export declare type MakeErrorData = StripErrorKeys<ZodSuberrorOptionalMessage>;
export declare type MakeErrorData = StripErrorKeys<ZodSuberrorOptionalMessage> & {
path?: (string | number)[];
};
export declare const ZodParser: (schemaDef: z.ZodTypeDef) => (obj: any, baseParams?: ParseParams) => any;
export {};

@@ -131,3 +131,3 @@ "use strict";

: defaultErrorMap_1.defaultErrorMap(errorArg, __assign({}, ctxArg, { defaultError: "Invalid value." }));
return __assign({}, errorData, { path: params.path, message: errorData.message || params.errorMap(errorArg, __assign({}, ctxArg, { defaultError: defaultError.message })).message });
return __assign({}, errorData, { path: params.path.concat((errorData.path || [])), message: errorData.message || params.errorMap(errorArg, __assign({}, ctxArg, { defaultError: defaultError.message })).message });
};

@@ -134,0 +134,0 @@ var def = schemaDef;

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {

@@ -44,54 +9,50 @@ if (mod && mod.__esModule) return mod;

};
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var z = __importStar(require("."));
var run = function () { return __awaiter(_this, void 0, void 0, function () {
var errorMap;
return __generator(this, function (_a) {
errorMap = function (error, ctx) {
/*
If error.message is set, that means the user is trying to
override the error message. This is how method-specific
error overrides work, like this:
z.string().min(5, { message: "TOO SMALL 🤬" })
It is a best practice to return `error.message` if it is set.
*/
if (error.message)
return { message: error.message };
/*
This is where you override the various error codes
*/
switch (error.code) {
case z.ZodErrorCode.invalid_type:
if (error.expected === 'string') {
return { message: "This ain't a string!" };
}
break;
case z.ZodErrorCode.custom_error:
// produce a custom message using error.params
// error.params won't be set unless you passed
// a `params` arguments into a custom validator
var params = error.params || {};
if (params.myField) {
return { message: "Bad input: " + params.myField };
}
break;
}
// fall back to default message!
return { message: ctx.defaultError };
};
try {
z.string().parse(12, { errorMap: errorMap });
}
catch (err) {
console.log(JSON.stringify(err.errors, null, 2));
}
return [2 /*return*/];
});
}); };
run();
z.object({
password: z.string(),
confirm: z.string(),
})
.refine(function (data) { return data.confirm === data.password; }, { path: ['confirm'] })
.parseAsync({ password: 'asdf', confirm: 'qewr' })
.catch(function (err) { return console.log(JSON.stringify(err, null, 2)); });
// const run = async () => {
// const errorMap: z.ZodErrorMap = (error, ctx) => {
// /*
// If error.message is set, that means the user is trying to
// override the error message. This is how method-specific
// error overrides work, like this:
// z.string().min(5, { message: "TOO SMALL 🤬" })
// It is a best practice to return `error.message` if it is set.
// */
// if (error.message) return { message: error.message };
// /*
// This is where you override the various error codes
// */
// switch (error.code) {
// case z.ZodErrorCode.invalid_type:
// if (error.expected === 'string') {
// return { message: `This ain't a string!` };
// }
// break;
// case z.ZodErrorCode.custom_error:
// // produce a custom message using error.params
// // error.params won't be set unless you passed
// // a `params` arguments into a custom validator
// const params = error.params || {};
// if (params.myField) {
// return { message: `Bad input: ${params.myField}` };
// }
// break;
// }
// // fall back to default message!
// return { message: ctx.defaultError };
// };
// try {
// z.string().parse(12, { errorMap });
// } catch (err) {
// console.log(JSON.stringify(err.errors, null, 2));
// }
// };
// run();
//# sourceMappingURL=playground.js.map
import { ParseParams, MakeErrorData } from '../parser';
import { util } from '../helpers/util';
import { CustomError } from '../ZodError';
export declare enum ZodTypes {

@@ -35,7 +37,4 @@ string = "string",

check: (arg: T) => any;
message?: string;
params?: {
[k: string]: any;
};
};
path?: (string | number)[];
} & util.Omit<CustomError, 'code' | 'path'>;
export interface ZodTypeDef {

@@ -58,3 +57,3 @@ t: ZodTypes;

check(u: Type | unknown): u is Type;
refine: <Val extends (arg: Type) => any>(check: Val, message?: string | Pick<Check<Type>, "message" | "params">) => this;
refine: <Val extends (arg: Type) => any>(check: Val, message?: string | Pick<Check<Type>, "message" | "path" | "params">) => this;
refinement: (refinement: Check<Type>) => this;

@@ -61,0 +60,0 @@ protected _refinement: (refinement: InternalCheck<Type>) => this;

@@ -74,3 +74,3 @@ import { ZodParsedType } from './parser';

}
interface CustomError extends ZodSuberrorBase {
export interface CustomError extends ZodSuberrorBase {
code: typeof ZodErrorCode.custom_error;

@@ -77,0 +77,0 @@ params?: {

{
"name": "zod",
"version": "1.8.0-beta.2",
"version": "1.8.0-beta.3",
"description": "TypeScript-first schema declaration and validation library with static type inference",

@@ -5,0 +5,0 @@ "main": "./lib/src/index.js",

@@ -37,7 +37,8 @@ <p align="center">

- [Objects](#objects)
- [.nonstrict](#unknown-keys)
- [.shape](#shape-property)
- [.merge](#merging)
- [.extend](#extending)
- [.extend](#extending-objects)
- [.pick/.omit](#masking)
- [.partial/.deepPartial](#partials)
- [.nonstrict](#unknown-keys)
- [Records](#records)

@@ -188,7 +189,5 @@ - [Arrays](#arrays)

To learn more about error handling with Zod, jump to [Errors](#errors).
### Custom validation
`.refine(validator: (data:T)=>any, err?: string)`
`.refine(validator: (data:T)=>any, params?: RefineParams)`

@@ -200,14 +199,56 @@ 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.

```ts
const myString = z.string().refine(val => val.length <= 255, "String can't be more than 255 characters");
const myString = z.string().refine(val => val.length <= 255, {
message: "String can't be more than 255 characters",
});
```
Here is the type signature for `.refine`:
As you can see, `.refine` takes two arguments.
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.)
2. The second argument is a custom error message. Read more about error handling in Zod [here](#errors)
2. The second argument is a params object. You can use this to customize certain error-handling behavior:
Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of useful string validation functions.
```ts
type RefineParams = {
// override error message
message?: string;
// override error path
path?: (string | number)[];
// params object you can use to customize message
// in error map
params?: object;
};
```
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:
```ts
z.object({
password: z.string(),
confirm: z.string(),
})
.refine(data => data.confirm === data.password, {
message: "Passwords don't match",
path: ['confirm'],
})
.parse({ password: 'asdf', confirmPassword: 'qwer' });
```
Because you provided a `path` parameter, the resulting error will be:
```ts
ZodError {
errors: [{
"code": "custom_error",
"path": [ "confirm" ],
"message": "Invalid input."
}]
}
```
Note that the `path` is set to `["confirm"]`, so you can easily display this error underneath the "Confirm password" textbox.
j
## Type inference

@@ -242,2 +283,4 @@

> Check out [validator.js](https://github.com/validatorjs/validator.js) for a bunch of other useful string validation functions.
### Custom error messages

@@ -262,7 +305,5 @@

The final (optional) argument is a params object that lets you provide a custom error in the `message` field.
```ts
z.number().min(5);
z.number().max(5, { message: 'this👏is👏too👏big' });
z.number().max(5);

@@ -277,2 +318,8 @@ z.number().int(); // value must be an integer

You can optionally pass in a params object as the second argument to provide a custom error message.
```ts
z.number().max(5, { message: 'this👏is👏too👏big' });
```
## Objects

@@ -361,5 +408,5 @@

#### Augmentation
#### Extending objects
You can augment an object schema with the `.extend` method.
You can add additional fields an object schema with the `.extend` method.

@@ -366,0 +413,0 @@ > 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.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc