Skyrim
Skyrim

Reputation: 162

Decimal regular expression with zero

We have a regular expression given below:

/[^0-9\\.()]/g

However, it does not accepts user to enter 0, e.g. it says that 0.06 is invalid. I'd like to make such inputs also valid.

All we need is the above regular expression to accept 0 (zero) too.

Upvotes: 2

Views: 77

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You are trying to use the same regular expression for input sanitizing and validation. You cannot use the same regex to do both tasks.

After sanitizing, you can add validation step like this:

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

Sample code:

var str = 'abc0.06abc';
var newstr = str.replace(/[^0-9.()]/g, '');
if (/^\d*(?:\.\d+)*$/.test(str) == false) {
   console.log(newstr + " is valid");  
}
else {
  console.log(newstr + " is not valid");
}

See demo

Upvotes: 1

Skyrim
Skyrim

Reputation: 162

Thanks Drake. The link which you provided did the trick.

var str = '0.05';
var newstr = str.replace(/[^0-9\.()]/g, '');
console.log(newstr);

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

Try this regex by removing the ^:

/[0-9.()]/g

Upvotes: 2

Related Questions