Skip to content

Commit

Permalink
fix is numeric
Browse files Browse the repository at this point in the history
  • Loading branch information
ogroppo committed Dec 1, 2024
1 parent 475caa6 commit 0cb58b2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
7 changes: 7 additions & 0 deletions src/validators/isNumeric.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,28 @@ 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);
expect(isNumeric(" 1 ")).toBe(false);
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);
Expand Down
10 changes: 7 additions & 3 deletions src/validators/isNumeric.ts
Original file line number Diff line number Diff line change
@@ -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
);
};

0 comments on commit 0cb58b2

Please sign in to comment.