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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added native support for min and max date validations #1222

Merged
merged 5 commits into from
Jul 18, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions deno/lib/ZodError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,14 @@ export interface ZodTooSmallIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_small;
minimum: number;
inclusive: boolean;
type: "array" | "string" | "number" | "set";
type: "array" | "string" | "number" | "set" | "date";
}

export interface ZodTooBigIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_big;
maximum: number;
inclusive: boolean;
type: "array" | "string" | "number" | "set";
type: "array" | "string" | "number" | "set" | "date";
}

export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase {
Expand Down Expand Up @@ -360,6 +360,10 @@ export const defaultErrorMap = (
message = `Number must be greater than ${
issue.inclusive ? `or equal to ` : ``
}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be greater than ${
issue.inclusive ? `or equal to ` : ``
}${new Date(issue.minimum)}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
Expand All @@ -375,6 +379,10 @@ export const defaultErrorMap = (
message = `Number must be less than ${
issue.inclusive ? `or equal to ` : ``
}${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be smaller than ${
issue.inclusive ? `or equal to ` : ``
}${new Date(issue.maximum)}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
Expand Down
23 changes: 23 additions & 0 deletions deno/lib/__tests__/date.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// @ts-ignore TS6133
import { expect } from "https://deno.land/x/expect@v0.2.6/mod.ts";
const test = Deno.test;

import * as z from "../index.ts";

const benchmarkDate = new Date(2022, 10, 5);

const minCheck = z.date().min(benchmarkDate);
const maxCheck = z.date().max(benchmarkDate);

test("passing validations", () => {
minCheck.parse(new Date(benchmarkDate));
minCheck.parse(new Date(benchmarkDate.getTime() + 1));

maxCheck.parse(new Date(benchmarkDate));
maxCheck.parse(new Date(benchmarkDate.getTime() - 1));
});

test("failing validations", () => {
expect(() => minCheck.parse(benchmarkDate.getTime() - 1)).toThrow();
expect(() => maxCheck.parse(benchmarkDate.getTime() + 1)).toThrow();
});
65 changes: 64 additions & 1 deletion deno/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1004,13 +1004,18 @@ export class ZodBoolean extends ZodType<boolean, ZodBooleanDef> {
////////// ////////
///////////////////////////////////////
///////////////////////////////////////
type ZodDateCheck =
| { kind: "min"; value: number; message?: string }
| { kind: "max"; value: number; message?: string };
export interface ZodDateDef extends ZodTypeDef {
checks: ZodDateCheck[];
typeName: ZodFirstPartyTypeKind.ZodDate;
}

export class ZodDate extends ZodType<Date, ZodDateDef> {
_parse(input: ParseInput): ParseReturnType<this["_output"]> {
const parsedType = this._getType(input);

if (parsedType !== ZodParsedType.date) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
Expand All @@ -1020,6 +1025,7 @@ export class ZodDate extends ZodType<Date, ZodDateDef> {
});
return INVALID;
}

if (isNaN(input.data.getTime())) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
Expand All @@ -1028,14 +1034,71 @@ export class ZodDate extends ZodType<Date, ZodDateDef> {
return INVALID;
}

const status = new ParseStatus();
let ctx: undefined | ParseContext = undefined;

for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
Balastrong marked this conversation as resolved.
Show resolved Hide resolved
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
minimum: check.value,
type: "date",
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
Balastrong marked this conversation as resolved.
Show resolved Hide resolved
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
maximum: check.value,
type: "date",
});
status.dirty();
}
} else {
util.assertNever(check);
}
}

return {
status: "valid",
status: status.value,
value: new Date((input.data as Date).getTime()),
};
}

_addCheck(check: ZodDateCheck) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check],
});
}

min(minDate: Date, message?: errorUtil.ErrMessage) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message),
});
}

max(maxDate: Date, message?: errorUtil.ErrMessage) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message),
});
}

static create = (params?: RawCreateParams): ZodDate => {
return new ZodDate({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params),
});
Expand Down
12 changes: 10 additions & 2 deletions src/ZodError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,14 @@ export interface ZodTooSmallIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_small;
minimum: number;
inclusive: boolean;
type: "array" | "string" | "number" | "set";
type: "array" | "string" | "number" | "set" | "date";
}

export interface ZodTooBigIssue extends ZodIssueBase {
code: typeof ZodIssueCode.too_big;
maximum: number;
inclusive: boolean;
type: "array" | "string" | "number" | "set";
type: "array" | "string" | "number" | "set" | "date";
}

export interface ZodInvalidIntersectionTypesIssue extends ZodIssueBase {
Expand Down Expand Up @@ -360,6 +360,10 @@ export const defaultErrorMap = (
message = `Number must be greater than ${
issue.inclusive ? `or equal to ` : ``
}${issue.minimum}`;
else if (issue.type === "date")
message = `Date must be greater than ${
issue.inclusive ? `or equal to ` : ``
}${new Date(issue.minimum)}`;
else message = "Invalid input";
break;
case ZodIssueCode.too_big:
Expand All @@ -375,6 +379,10 @@ export const defaultErrorMap = (
message = `Number must be less than ${
issue.inclusive ? `or equal to ` : ``
}${issue.maximum}`;
else if (issue.type === "date")
message = `Date must be smaller than ${
issue.inclusive ? `or equal to ` : ``
}${new Date(issue.maximum)}`;
else message = "Invalid input";
break;
case ZodIssueCode.custom:
Expand Down
22 changes: 22 additions & 0 deletions src/__tests__/date.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// @ts-ignore TS6133
import { expect, test } from "@jest/globals";

import * as z from "../index";

const benchmarkDate = new Date(2022, 10, 5);

const minCheck = z.date().min(benchmarkDate);
const maxCheck = z.date().max(benchmarkDate);

test("passing validations", () => {
minCheck.parse(new Date(benchmarkDate));
minCheck.parse(new Date(benchmarkDate.getTime() + 1));

maxCheck.parse(new Date(benchmarkDate));
maxCheck.parse(new Date(benchmarkDate.getTime() - 1));
Balastrong marked this conversation as resolved.
Show resolved Hide resolved
});

test("failing validations", () => {
expect(() => minCheck.parse(benchmarkDate.getTime() - 1)).toThrow();
expect(() => maxCheck.parse(benchmarkDate.getTime() + 1)).toThrow();
});
65 changes: 64 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1004,13 +1004,18 @@ export class ZodBoolean extends ZodType<boolean, ZodBooleanDef> {
////////// ////////
///////////////////////////////////////
///////////////////////////////////////
type ZodDateCheck =
| { kind: "min"; value: number; message?: string }
| { kind: "max"; value: number; message?: string };
export interface ZodDateDef extends ZodTypeDef {
checks: ZodDateCheck[];
typeName: ZodFirstPartyTypeKind.ZodDate;
}

export class ZodDate extends ZodType<Date, ZodDateDef> {
_parse(input: ParseInput): ParseReturnType<this["_output"]> {
const parsedType = this._getType(input);

if (parsedType !== ZodParsedType.date) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
Expand All @@ -1020,6 +1025,7 @@ export class ZodDate extends ZodType<Date, ZodDateDef> {
});
return INVALID;
}

if (isNaN(input.data.getTime())) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
Expand All @@ -1028,14 +1034,71 @@ export class ZodDate extends ZodType<Date, ZodDateDef> {
return INVALID;
}

const status = new ParseStatus();
let ctx: undefined | ParseContext = undefined;

for (const check of this._def.checks) {
if (check.kind === "min") {
if (input.data.getTime() < check.value) {
Balastrong marked this conversation as resolved.
Show resolved Hide resolved
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
minimum: check.value,
type: "date",
});
status.dirty();
}
} else if (check.kind === "max") {
if (input.data.getTime() > check.value) {
Balastrong marked this conversation as resolved.
Show resolved Hide resolved
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
maximum: check.value,
type: "date",
});
status.dirty();
}
} else {
util.assertNever(check);
}
}

return {
status: "valid",
status: status.value,
value: new Date((input.data as Date).getTime()),
};
}

_addCheck(check: ZodDateCheck) {
return new ZodDate({
...this._def,
checks: [...this._def.checks, check],
});
}

min(minDate: Date, message?: errorUtil.ErrMessage) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil.toString(message),
});
}

max(maxDate: Date, message?: errorUtil.ErrMessage) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil.toString(message),
});
}

static create = (params?: RawCreateParams): ZodDate => {
return new ZodDate({
checks: [],
typeName: ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params),
});
Expand Down