user850234
user850234

Reputation: 3463

Validation of proper number value

The regex /^-?\d*(\.\d+)?$/ does the proper validation for both negative and positive integer as well as decimal values. But I want the regex to be extended a bit to address the following also :

  1. The value can be 0 but should not be -0. Only if it a floating value like 0.1 than the negative value should be supported.
  2. Any number should not start with leading zero other than integer 0 itself or decimal values starting with 0.1 as for example. But there should not be any value like 00 or 00.01.
  3. Validation of empty value.

The idea is to make sure a single regex does the complete validation instead of doing multiple checks.

Upvotes: 2

Views: 66

Answers (3)

ilmirons
ilmirons

Reputation: 664

I think this should work:

/^(0|-?(0.\d+|[1-9]\d*(\.?(\d+))?))$/

Upvotes: 1

OGHaza
OGHaza

Reputation: 4795

Heavily influenced by ilmirons answer:

^(0|-?(0\.\d+|[1-9]\d*(\.\d+)?))$

RegExr

Upvotes: 1

halkujabra
halkujabra

Reputation: 2942

  function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }

Upvotes: 0

Related Questions