Skip to content

Commit

Permalink
feat: Add scientific notation support to isNumeric validator
Browse files Browse the repository at this point in the history
- Updated the `isNumeric` function to handle scientific notation values.
- Modified the regular expression to account for both positive and negative exponents, using `e` or `E`.
- Introduced an option to handle locales with different decimal separators.
- Preserved backward compatibility by ensuring that the `no_symbols` option continues to function correctly.
- This change ensures that inputs like `1e5`, `1.23E-5`, and other variations of scientific notation are now validated properly.
  • Loading branch information
VivekHalder committed Oct 1, 2024
1 parent ff56dcf commit f888607
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/lib/isNumeric.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,17 @@ import { decimal } from './alpha';

const numericNoSymbols = /^[0-9]+$/;

export default function isNumeric(str, options) {
assertString(str);
if (options && options.no_symbols) {
return numericNoSymbols.test(str);
}
return (new RegExp(`^[+-]?([0-9]*[${(options || {}).locale ? decimal[options.locale] : '.'}])?[0-9]+$`)).test(str);
export default function isNumeric(str, options = { no_symbols: false }) {
assertString(str); // verify if the str is a string, if not report a TypeError

// destructure options to extract the required properties
const { locale, no_symbols } = options;

// deciding the separator upfront (default separator is '.')
const decimalSeparator = locale ? decimal[locale] : '.';

// setting the regex depending on the value of no_symbols
const regex = no_symbols ? numericNoSymbols : `^[+-]?([0-9]*[${ decimalSeparator }])?[0-9]+([eE][+-]?[0-9]+)?$`;

return regex.test(str);
}

0 comments on commit f888607

Please # to comment.