Reputation: 35
I am new to regular expressions and i would like to validate user input with javascript.
The user input is a currency, but i want it without the thousands commata.
Valid
"12.34"
"12,34"
"1234,5"
"123"
"123,00"
"12000"
Invalid
"12a34"
"abc"
"12.000,00"
"12,000.00"
I tried the following regex-pattern, but it doesnt work for me. it validates for example "12a34" and i dont know why.
/\d+([\.|\,]\d+)?/
What would be the correct regex-pattern ? Could you explain this step by step ?
Thanks !
Upvotes: 0
Views: 701
Reputation: 2334
RegExp: /^(?!\(.*[^)]$|[^(].*\)$)\(?\$?(0|[1-9]\d{0,2}(,?\d{3})?)(\.\d\d?)?\)?$/g
pattern: ^(?!\(.*[^)]$|[^(].*\)$)\(?\$?(0|[1-9]\d{0,2}(,?\d{3})?)(\.\d\d?)?\)?$
flags: g
3 capturing groups:
group 1: (0|[1-9]\d{0,2}(,?\d{3})?)
group 2: (,?\d{3})
group 3: (\.\d\d?)
Upvotes: -1
Reputation: 152216
Do not escape the .
while in a character group. Try with following regex:
/^\d+([.,]\d{1,2})?$/
^ = start of string
$ = end of string
()? = an optional capturegroup ( e.g. to validate "123")
{x,y} = The symbol may occur minimum x and maximum y times
Upvotes: 3