最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex for decimal number with optional decimal point - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Sep 8, 2016 at 9:46 niklodeonniklodeon 1,3807 gold badges25 silver badges52 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 22

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})?" />

发布评论

评论列表(0)

  1. 暂无评论