0

I have an input text and I want to allow only numbers(positive and negative) with only one special character for each "." and "-". For example you can have -12.30, but -12...20 or --12.40 it is not allowed.

Currently I have this:

value.replace(/[^\d|.-]/g, "");

which allows multiple "." and "-".

Ovidiu Ionut
  • 1,452
  • 1
  • 8
  • 14

2 Answers2

3

You can use this

^[+-]?\d+(?:\.\d+)?$

enter image description here

let testStr = (str) => /^[+-]?\d+(?:\.\d+)?$/.test(str)

console.log(testStr('123.12'))
console.log(testStr('-123..123'))
console.log(testStr('---12332'))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Ok. I understand, but I need to replace everything that is not matching this regular expression. So I can negate this and replace with ""? Like I did above(value.replace(/RegExp/, "")) – Ovidiu Ionut Aug 28 '19 at 14:49
3

As you don't need the + before the number, a simpler one is ^-?\d+(?:\.\d+)?$

  • ^ = start of the line
  • -? = make - optional
  • \d+ = between at least 1 digit and unlimited digits
  • (?:) = non-capturing group
  • (?:)? = optional non-capturing group
  • (?:\.\d+) = optional non-capturing group that contains one . and between 1 and unlimited digits, after the .
Stéphane Damon
  • 231
  • 2
  • 6