Gabriel Spiteri
Gabriel Spiteri

Reputation: 4978

Regex to allow negative values

I am hoping to find someone here which can give me a hand with some regex I need to modify.

This regex is being used in JavaScript for some validation:

/^([A-Z]{3} [0-9]+\.[0-9]{1,2}(, )?)+$/

This will correctly validate the following values:

EUR 20.3, USD 9.0

GBP 8.8

I would like to modify the regex to also accept negative values such as:

EUR -20.3, USD -9.0

I thank you for your help :)

Regards Gabriel

Upvotes: 2

Views: 5689

Answers (3)

Gareth Davis
Gareth Davis

Reputation: 28059

surely just add in:

-?

which should optionally match '-'

/^([A-Z]{3} -?[0-9]+\.[0-9]{1,2}(, )?)+$/

Upvotes: 5

herostwist
herostwist

Reputation: 3958

try this:

/^([A-Z]{3} -?[0-9]+(\.[0-9]{1,2})?,?)+$/

the decimal places are now optional

GBP -1, GBP -1.1 should be valid

Upvotes: 0

Yoann
Yoann

Reputation: 5077

In the exact same way you check for the coma , but xith negative signe -

Try something like this ([A-Z]{3} -?[0-9]+.[0-9]{1,2},?)+

Upvotes: 1

Related Questions