niklodeon
niklodeon

Reputation: 1380

Regex for decimal number with optional decimal point

My requirement is to test the pasted data and if it fails then don't paste.

Regex: /\d{0,4}([\.|\,]\d{0,2})?/

Data used:

1.2 tests true
1.2.3 test true as well

Requirement is

min 0 max 4 digits before decimal point
decimal point can be either dot or comma
min 1 max 3 digits after decimal point if there exists a decimal point.

I have tried following but does not work.
Any help will be appreciated.

fiddle

Upvotes: 9

Views: 12705

Answers (1)

Tushar
Tushar

Reputation: 87203

From your requirements

/^\d{0,4}(?:[.,]\d{1,3})?$/
  1. ^: Start of the line
  2. \d{0,4}: Zero-to-four digits
  3. [.,]: Match dot or comma
  4. \d{1,3}: One-to-three digits
  5. (?: ... ): Non-capturing group
  6. (something)? The group can occur zero or once
  7. $: End of line

input:valid {
  color: green;
  font-weight: bold
}
input:invalid {
  color: red;
}
<input type="text" pattern="\d{0,4}(?:[.,]\d{1,3})?" />

Upvotes: 22

Related Questions