maydawn
maydawn

Reputation: 528

Only allow positive and negative 2 point decimal directive

I needed a directive to allow only 2 point decimals and I found this answer https://stackoverflow.com/a/27163833/5229041

However, I can't seem to figure out how to fix the regex to also allow an optional - for negative numbers as well.

(I tried asking in the answer comments, but I'm not allowed to)

Upvotes: 0

Views: 1946

Answers (2)

Marco Moretti
Marco Moretti

Reputation: 689

You have to simply change this line

var clean = val.replace(/[^0-9\.]/g, '');

with this

var clean = val.replace(/(?!^-)[^0-9\.]/g, '');

Upvotes: 1

Fallenhero
Fallenhero

Reputation: 1583

In regex -? means - is optional. So just add that

Upvotes: 1

Related Questions