Skip to content

Commit

Permalink
Allow undefined/null values on optional integer number schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
Bartmr committed Dec 18, 2021
1 parent 97bd260 commit e010c0c
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "not-me",
"version": "4.3.4",
"version": "4.3.5",
"description": "Easy and type-safe validation",
"main": "lib/index.js",
"types": "lib/types.d.ts",
Expand Down
9 changes: 9 additions & 0 deletions src/schemas/number/number-schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,13 @@ describe("Number Schema", () => {
value: 123.3,
});
});

it("Let undefined pass an integer check, if number is not required", () => {
const schema: Schema<number | undefined | null> = number().integer();

expect(schema.validate(undefined)).toEqual({
errors: false,
value: undefined,
});
});
});
20 changes: 12 additions & 8 deletions src/schemas/number/number-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,18 @@ class NumberSchemaImpl<_Output = number | undefined | null> extends BaseSchema<
}

integer(message?: string): this {
this.test((input) =>
Number.isInteger(input)
? null
: message ||
DefaultErrorMessagesManager.getDefaultMessages().number
?.isNotInteger ||
"Input must be an integer"
);
this.test((input) => {
if (input == null) {
return null;
} else {
return Number.isInteger(input)
? null
: message ||
DefaultErrorMessagesManager.getDefaultMessages().number
?.isNotInteger ||
"Input must be an integer";
}
});

return this;
}
Expand Down

0 comments on commit e010c0c

Please sign in to comment.