0

I want my ExtJS textfield to allow only numbers and decimals (Both positve and negative) .I need a regex to allow an integer or decimal number which can be positive or negative . Should match -

1) 123
2) 123.23
3) -123
4) -123.23

Should not match for
1) --123
2) -2323-
3) 23.23.23
4) 34..34

Harshal
  • 961
  • 1
  • 11
  • 26

3 Answers3

2

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

Tested it and it works on

0
1
12
123
0.1
1.12
12.0123
-1
-12
-0.1
-1.12
-12.0123
-0

And dosnt work on:

--123
-2323-
23.23.23
34..34
aifrim
  • 555
  • 9
  • 20
1
^-?(0|([1-9][0-9]*))(\.[0-9]+)?$

it doesn't work with

  • 0123 due to leading 0 is meaningless
    1. due to without number after decimal
  • .123 due to without number before decimal

https://regex101.com/r/d3q4TI/1 to try it out

Simon
  • 1,426
  • 3
  • 16
  • 24
-1

try this

const regex = /^([-])?\d+(\.\d+)?$/

const validInputs = [123, 123.23, -123, -123.23, '-123.23', '-01.123']
const invalidInputs = ['--123', '-2323-', '23.23.23', '34..34']

for (const item of validInputs) {
  console.log(`test ${item} => ${regex.test(item)}`)
}

console.log('=======================')

for (const item of invalidInputs) {
  console.log(`test ${item} => ${regex.test(item)}`)
}
Alongkorn
  • 3,968
  • 1
  • 24
  • 41