Arjun Prajapati
Arjun Prajapati

Reputation: 273

Regex to allow only a single dot in a textbox

I have one text input.

I wrote a regex for masking all special characters except . and -. Now if by mistake the user enters two . (dots) in input, then with the current regex

var valueTest='225..36'

valueTest.match(/[^-.\d]/)

I expected that the number will not pass this condition

How to handle this case. I just want one . (dot) in input field since it is a number.

Upvotes: 6

Views: 22139

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174874

I think you mean this,

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

DEMO

It allows positive and negative numbers with or without decimal points.

EXplanation:

  • ^ Asserts that we are at the start.
  • -? Optional - symbol.
  • \d+ Matches one or more numbers.
  • (?: start of non-capturing group.
  • \. Matches a literal dot.
  • \d+ Matches one or more numbers.
  • ? Makes the whole non-capturing group as optional.
  • $ Asserts that we are at the end.

Upvotes: 12

Tim.Tang
Tim.Tang

Reputation: 3188

if you just want to handle number ,you can try this:

valueTest.match(/^-?\d+(\.\d+)?$/)

Upvotes: 3

Mitul
Mitul

Reputation: 131

Use below reg ex it will meet your requirements.

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

Upvotes: 2

Mena
Mena

Reputation: 48444

You can probably avoid regex altogether with this case.

For instance

String[] input = { "225.36", "225..36","-225.36", "-225..36" };
for (String s : input) {
    try {
        Double d = Double.parseDouble(s);
        System.out.printf("\"%s\" is a number.%n", s);
    }
    catch (NumberFormatException nfe) {
        System.out.printf("\"%s\" is not a valid number.%n", s);
    }
}

Output

"225.36" is a number.
"225..36" is not a valid number.
"-225.36" is a number.
"-225..36" is not a valid number.

Upvotes: 2

Related Questions