Martin
Martin

Reputation: 557

Validating Currency using JavaScript

I am using a Js regular expression to validate currency of sterling pounds (670 , 170p , £17.98p , £56.90867 , 007.89p) and should not allow the following values( 19x , 18p.12 , £p ) but it keeps failing,,,

~ Any help will be highly appreciated

 var reg= /^£?[1-9]{1,3}(,\d{3})*(\.\d{2})?$/ ;

Upvotes: 0

Views: 350

Answers (3)

Taha Paksu
Taha Paksu

Reputation: 15616

The closest regex is :

£?\d+(?:\.\d+)?p?\b

Test File: https://regex101.com/r/09wjc7/1

But it only fails with 18p.12 because it matches two groups of it. First 18p is valid and second 12 is valid.

If you are looking it inside a text, you can add text boundaries to it, but if you are looking it by line, you can add ^(Start of Line) and $(End of line) characters to the regex, which will ignore the case above.

Explanation:

  • £? An optional £ sign before the group
  • \d+ Required integer (one or more)
  • (?:\.\d+)?
    • (?: start of non matching group
    • \. Dot Character
    • \d+ Required integer (one or more)
    • )? Make all of this group optional
  • p? Optional p character
  • \b should end with a word boundary. https://www.regular-expressions.info/wordboundaries.html

Upvotes: 1

Demilade
Demilade

Reputation: 513

This should work var regex = /^£?\d{1,3}(,\d{3})*(\.\d{2})?p?$/

var currencyString = '£56.78p'
regex.test(currenceString) === true

Upvotes: 0

Wilson Wong
Wilson Wong

Reputation: 406

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

The issue with [1-9]{1,3} is it does not match any strings with 0, so 670 would fail to match.

Upvotes: 0

Related Questions