30secondstosam
30secondstosam

Reputation: 4686

Regular expression for currency field

Please can someone help me to write a JavaScript regular expression? I need to write a field that will allow examples of the following:

£1, £1.00, 1p

I do not want it to allow £ and p together. I also don't want it to allow more than 1 decimal. So far, I have the following:

/^(\u00A3)?([0-9\.]+)p?$/ 

This doesn't work 100% accurately though. Any help or guidance would be really appreciated. Thanks

Upvotes: 1

Views: 296

Answers (2)

Jerry
Jerry

Reputation: 71538

You might try this regex:

^(?:\u00A3([0-9]+(?:\.[0-9]{1,2})?)|[0-9]+p)$

regex101 demo

This will allow up to 2dp for pounds. If you want to allow more, just use + instead:

^(?:\u00A3([0-9]+(?:\.[0-9]+)?)|[0-9]+p)$

Also, I didn't put decimals for pence. If you want to allow those too, you can use:

^(?:\u00A3([0-9]+(?:\.[0-9]{1,2})?)|[0-9]+(?:\.[0-9]{1,2})?p)$

Upvotes: 2

Toto
Toto

Reputation: 91415

How about:

/^(\u00A3[0-9\.]+)|([0-9\.]+p)$/ 

Upvotes: 1

Related Questions