NaN option

This commit is contained in:
Sebastian Seedorf
2020-05-26 20:35:54 +02:00
parent 836b1449bf
commit d33ce96d18
2 changed files with 12 additions and 2 deletions

View File

@@ -19,6 +19,7 @@ Deno.test("isNumber (match)", async () => {
for (const value of values) {
assertEquals(await validate(value, isNumber()), []);
}
assertEquals(await validate(NaN, isNumber({ allowNaN: true })), []);
});
Deno.test("isNumber (no match)", async () => {
@@ -35,6 +36,7 @@ Deno.test("isNumber (no match)", async () => {
for (const value of values) {
assertNotEquals(await validate(value, isNumber()), []);
}
assertNotEquals(await validate(NaN, isNumber({ allowNaN: false })), []);
});
Deno.test("isInteger (match)", async () => {
@@ -49,6 +51,7 @@ Deno.test("isInteger (match)", async () => {
for (const value of values) {
assertEquals(await validate(value, isInteger()), []);
}
assertEquals(await validate(NaN, isInteger({ allowNaN: true })), []);
});
Deno.test("isInteger (no match)", async () => {
@@ -66,4 +69,5 @@ Deno.test("isInteger (no match)", async () => {
for (const value of values) {
assertNotEquals(await validate(value, isInteger()), []);
}
assertNotEquals(await validate(NaN, isInteger({ allowNaN: false })), []);
});

View File

@@ -1,10 +1,13 @@
import { Validator, Args } from "../mod.ts";
export function isNumber(): Validator {
export function isNumber(
{ allowNaN = false }: { allowNaN?: boolean } = {},
): Validator {
return {
type: "isNumber",
check: (value: any) => {
if (value === null || value === undefined) return;
if (allowNaN && Number.isNaN(value)) return;
if (!Number.isFinite(value)) {
return {};
}
@@ -15,11 +18,14 @@ export function isNumber(): Validator {
};
}
export function isInteger(): Validator {
export function isInteger(
{ allowNaN = false }: { allowNaN?: boolean } = {},
): Validator {
return {
type: "isInteger",
check: (value: any) => {
if (value === null || value === undefined) return;
if (allowNaN && Number.isNaN(value)) return;
if (!Number.isInteger(value)) {
return {};
}