0

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 !

1

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this works for me. What does the ^ and the $ mean for this pattern ?
^ means that you are matching regex from the first character of the string and $ to the end. Without it, regex can match just a part of the string.
+1 just to mention that if you want to match up to 2 digits after the decimal point you can use \d{1,2} instead of \d+
Thanks for updating the answer, really helps me understanding regex!
-1
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?)

Regex Test

2 Comments

Links rot - and then your answer is useless.
In other words, give an answer here. You can also provide a link to a fiddle or test site, but that other site is not going to be around forever. Answers (and examples and questions as well!) should be self-contained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.