diff --git a/src/validators/isNumeric.test.ts b/src/validators/isNumeric.test.ts index 8090020..8bd1bf6 100644 --- a/src/validators/isNumeric.test.ts +++ b/src/validators/isNumeric.test.ts @@ -6,14 +6,19 @@ describe("isNumeric", function () { expect(isNumeric("33")).toBe(true); expect(isNumeric("-33")).toBe(true); expect(isNumeric("2e12")).toBe(true); + expect(isNumeric("2E-5")).toBe(true); expect(isNumeric("2.22")).toBe(true); expect(isNumeric(".22")).toBe(true); expect(isNumeric("0xff")).toBe(true); + expect(isNumeric("0xF")).toBe(true); + expect(isNumeric("0Xabc123")).toBe(true); expect(isNumeric("0b11111111")).toBe(true); + expect(isNumeric("0B0")).toBe(true); expect(isNumeric("0.255e3")).toBe(true); }); it("checks false", function () { + expect(isNumeric("570f0248-1e00-4cbf-9a01-ea1fe20ce0b5")).toBe(false); expect(isNumeric("string")).toBe(false); expect(isNumeric("")).toBe(false); expect(isNumeric(" ")).toBe(false); @@ -21,6 +26,8 @@ describe("isNumeric", function () { expect(isNumeric("1 3")).toBe(false); expect(isNumeric("..1")).toBe(false); expect(isNumeric("\t")).toBe(false); + expect(isNumeric("0B2")).toBe(false); + expect(isNumeric("0xzy")).toBe(false); expect(isNumeric("\n")).toBe(false); expect(isNumeric("\r")).toBe(false); expect(isNumeric(Infinity)).toBe(false); diff --git a/src/validators/isNumeric.ts b/src/validators/isNumeric.ts index d1188eb..a05fad8 100644 --- a/src/validators/isNumeric.ts +++ b/src/validators/isNumeric.ts @@ -1,18 +1,22 @@ import { isNumber } from "./isNumber"; -import { isSpacedString } from "./isSpacedString"; import { isString } from "./isString"; /** * * @example isNumeric(1) => true + * @example isNumeric(10e8) => true * @example isNumeric('1') => true * @example isNumeric('1.1') => true * @example isNumeric('1.1.1') => false + * @example isNumeric('1-1') => false */ export const isNumeric = (arg: number | string): boolean => { if (isNumber(arg)) return true; - if (!isString(arg) || isSpacedString(arg)) return false; + // safety check, no other types are allowed + if (!isString(arg)) return false; - return !isNaN(parseFloat(arg)); + return /^[+-]?((\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?|0[xX][\dA-Fa-f]+|0[bB][01]+)$/.test( + arg + ); };