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

javascript - angularjs ng-pattern regex for 4 digits and 2 decimal - Stack Overflow

programmeradmin2浏览0评论

I am trying to create a Regex for a number with maximum 4 digits and if the input has decimal it has to have 2 digits - .20 and not .1. tried:

ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" //fail for 666666, .10, .1

Examples for valid inputs:

100.10
100
3000.10

Example for invalid:

10000 //has more then 4 digits before decimal
100.1 //has only 1 digit after decimal
.10 //has no digits before decimal

Thanks for any help.

I am trying to create a Regex for a number with maximum 4 digits and if the input has decimal it has to have 2 digits - .20 and not .1. tried:

ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" //fail for 666666, .10, .1

Examples for valid inputs:

100.10
100
3000.10

Example for invalid:

10000 //has more then 4 digits before decimal
100.1 //has only 1 digit after decimal
.10 //has no digits before decimal

Thanks for any help.

Share Improve this question edited Oct 1, 2017 at 7:42 Itsik Mauyhas asked Oct 1, 2017 at 7:37 Itsik MauyhasItsik Mauyhas 4,00415 gold badges74 silver badges119 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Use {#,#} to limit the number of digits to 1 to 4

Try

^[0-9]{1,4}(\.[0-9][0-9])?$

Use ( )? to make an optional two-digit decimal part

The problem with using the {1,2} is that it allows one or two digits, when you really only want two. And I assume you want to enforce a rule that if they have a ".", they must have two digits?

For example

var patt = /^[0-9]{1,4}(\.[0-9][0-9])?$/i

"1011.11".match(patt)!==null
"1011.1".match(patt)!==null

Returns

true
false

With gratitude to Sebastian Proske and Wiktor Stribiżew

For pointing out the need to escape the .

发布评论

评论列表(0)

  1. 暂无评论