cmarin
cmarin

Reputation: 59

Javascript regex positive negative decimal number

I need a regex that would match a positive and negative decimal value, empty string ('') and also minus only ('-'). Since I need it inside the function that handles the change of a numeric field and in order to add a negative value the user firstly adds the "-" or deletes the old value (""), I need to match all these 3 conditions.

So, to sum up, the regex should allow:

What I have until now is:

function sanitizeInputValue(value: string) {
  var re = new RegExp('^$|^-?\\d{1,9}(\\.\\d{1,2})?$');
  return value.match(re) === null ? 0 : value;
}

Upvotes: 0

Views: 1423

Answers (3)

The fourth bird
The fourth bird

Reputation: 163362

You can make matching the digits with decimal parts optional so you would also match the hyphen only ^$|^-?(?:\d{1,9}(\.\d{1,2})?)?$

As then all parts are optional, you can omit the ^$ and then all parts are optional.

^-?(?:\d{1,9}(?:\.\d{1,2})?)?$

Explanation

  • ^ Start of string
  • -? Optional hyphen
  • (?: Non capture group
    • \d{1,9} match 1-9 times a digit
    • (?:\.\d{1,2})? Optionally match a dot and 1-2 digits
  • )? Close non capture group and make it optional as well
  • $ End of string.

Regex demo

var re = new RegExp("^-?(?:\\d{1,9}(?:\\.\\d{1,2})?)?$");

[
  "",
  "-",
  "1",
  "1.2",
  "test",
  "1234567890",
  "1.123",
  "-2",
  "-2.6"
].forEach(s => console.log(s + " --> " + re.test(s)));

Edit

As you also want to match -8. and don't want to limit the amount of digits, you could use:

^-?(?:\d+\.?\d*)?$

Explanation

  • ^ Start of string
  • -? Optional -
  • (?: Non capture group
    • \d+\.?\d* Match 1+ digits, optional dot and 0+ digits
  • )? Close group and make it optional
  • $ End of string

Regex demo

var re = new RegExp("^-?(?:\\d+\\.?\\d*)?$");
[
  "-8.",
  "",
  "-",
  "1",
  "1.2",
  "test",
  "1234567890",
  "1.123",
  "-2",
  "-2.6"
].forEach(s =>
  console.log(s + " --> " + re.test(s))
);

Upvotes: 1

Petr Savchenko
Petr Savchenko

Reputation: 194

function sanitizeInputValue(value) {
  var re = /^$|\-?[0-9]\d*(\.\d*)?|-/;
  return value.match(re) ? value : 0;
}

Upvotes: 0

Ahmad
Ahmad

Reputation: 12737

Use javascript's built in Number to convert the string into a numeric value right before you return from the function.

Also, I modified your regex so that it can accept input like .23 and 0.2345.

function sanitizeInputValue(value) {
  var re = new RegExp('^$|^-?(\\d+)?(\\.?\\d*)?$');
  return value.match(re) === null ? 0 : Number(value);
}

console.log(sanitizeInputValue("-23"));     // -23
console.log(sanitizeInputValue("42.123"));  //  42.123
console.log(sanitizeInputValue("-.34"));    // -0.34
console.log(sanitizeInputValue(""));        //  0
console.log(sanitizeInputValue("-8."));     //  -8
console.log(sanitizeInputValue("-8.4"));     // -8.4

Upvotes: 1

Related Questions