validatorjs / validator.js

String validation
MIT License
23.12k stars 2.31k forks source link

`isNumeric` doesn't support scientific notation #2430

Open benada002 opened 4 months ago

benada002 commented 4 months ago

Describe the bug 👋 Not sure if you consider this a 🐛, but I just noticed that isNumeric doesn't support scientific notation. Eg. this works perfectly fine (returns true):

const testNumber = (200000000000000000000).toString()
validator.isNumeric(testNumber)

But this returns false, even through it's a valid number

// Results in "2e+21"
const testNumberFailing = (2000000000000000000000).toString()
validator.isNumeric(testNumberFailing)

Examples image

Reproductions https://runkit.com/embed/xsw1bpnhjcgs

SuvitsonHarrese commented 4 months ago

@benada002 I have added a regex to handle scientific notation ^[+-]?([0-9]*[\.?])?[0-9]+(e(\+|\-)[0-9]+)?$

To handle the scientific notation you have to edit isNumeric.js file or you can copy the below code and paste it in that file where I have added the regex function in return statement

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = isNumeric;
var _assertString = _interopRequireDefault(require("./util/assertString"));
var _alpha = require("./alpha");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var numericNoSymbols = /^[0-9]+$/;
function isNumeric(str, options) {
  (0, _assertString.default)(str);
  if (options && options.no_symbols) {
    return numericNoSymbols.test(str);
  }
       return new RegExp("^[+-]?([0-9]*[".concat((options || {}).locale ? _alpha.decimal[options.locale]+"])?[0-9]+$" : ".])?[0-9]+(e(\\+|\\-)[0-9]+)?$")).test(str);

}
module.exports = exports.default;
module.exports.default = exports.default;
rubiin commented 2 months ago

@SuvitsonHarrese you can make a pr if you like

ShreySinha02 commented 2 months ago

@benada002 @SuvitsonHarrese @rubiin #2447 I had made a PR related to this issue. Could you please review it? 🙏