Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
862 views
in Technique[技术] by (71.8m points)

regex - HTML5 Form Input Pattern Currency Format

Using HTML5 I have an input field that should validate against a dollar amount entered. Currently I have the following markup:

<input type="number" pattern="(d{3})([.])(d{2})">

This works great for an amount that is greater than 100.00 and less than 1,000.00. I am trying to write the pattern (regex) to accept different dollar amounts. Maybe upwards of 100,000.00. Is this possible?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The best we could come up with is this:

^\$?(([1-9](\d*|\d{0,2}(,\d{3})*))|0)(\.\d{1,2})?$

I realize it might seem too much, but as far as I can test it matches anything that a human eye would accept as valid currency value and weeds out everything else.

It matches these:

1 => true
1.00 => true
$1 => true
$1000 => true
0.1 => true
1,000.00 => true
$1,000,000 => true
5678 => true

And weeds out these:

1.001 => false
02.0 => false
22,42 => false
001 => false
192.168.1.2 => false
, => false
.55 => false
2000,000 => false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...