Home > Software design >  How to use Regex to limit user input to numeric fields, with one allowed decimal and one allowed neg
How to use Regex to limit user input to numeric fields, with one allowed decimal and one allowed neg

Time:11-22

I am trying to only allow numeric values, along with a possible negative symbol at the front of the string, and a single decimal, using Regex in JavaScript. This input value will only allow for a possible 10 digits also.

Currently, when a user inputs text, I have this logic that will only allow numbers, negative signs, and decimals. However, I want to limit the number of the negative sign to one, and only allow this at the front of the string. Also, I want to limit the number of decimals to one.

input.slice(0, 10).replace(/[^0-9.\-]/, '');

Can anyone please help me figure this out?

CodePudding user response:

You can do:

input.slice(0, 10).match(/([-]?)([0-9] )([.]?)([0-9]?)/);

CodePudding user response:

Short n sweet.

/^-?\d{0,10}(\.\d{0,3})?$/
  • optional negative char. at the start
  • allows max of 10 digits next
  • again optional decimal group with at most 3 decimal places

These barriers can be modified accordingly.

  • Related