开发者

Price Field Regular Expression Without Prefixed 0 for Cents

开发者 https://www.devze.com 2023-03-27 02:38 出处:网络
I\'m using the following regular expression to validate a price field: (\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2开发者_JAVA百科})?$

I'm using the following regular expression to validate a price field:

(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2开发者_JAVA百科})?$

It works absolutely perfectly except for when a user types in a price of the form .60, etc. If I add a 0 in front, like 0.60, it seems to work fine, but I would like to allow the user to ommit the 0 as a prefix.


Use this syntax for (optional_subgroup)? i.e. nest in another pair of parentheses '(...)' and append '?'

In your case, the entire integer subpart (\d{1,3}(\,\d{3})*|(\d+)) is optional. Hence

((\d{1,3}(\,\d{3})*)|(\d+))?(\.\d{2})?$

However now this will match totally empty expressions, i.e. 0 integer and 0 decimal digits. So we must require either at least 1 integer digit (+ optional decimal part)...

((\d{1,3}(\,\d{3})*)|(\d+))(\.\d{2})?

or at least 2 decimal digits (+ optional integer part))...

((\d{1,3}(\,\d{3})*)?|(\d+))(\.\d{2})

So match either of those two (INTEGER)(DECIMAL)?|(INTEGER)?(DECIMAL) - we could compress your regex if you tell us more.

Alternatively, postprocess the match (in ASP) to reject the 0 integer + 0 decimal digits case. (Can you post that ASP snippet?)

Don't match a decimal point all by itself. It's up to you whether you allow a single decimal digit: .1


(\d{1,3}(\,\d{3})*|(\d*))(\.\d{2})?$
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号