I need to validate some form fileds that contain brazilian money (its name is "Real") using Javascript. It has the following format:
0,01
0,12
1,23
12,34
123,45
1.234,56
12.235,67
123.456,78
1.234.567,89
12.345.678,90
123.456.789,01
1.234.567.890,12
My regex knowledge is weak, can somebody help me please?
To validate currency with JavaScript regex, we use the following regex: The (?=.*?\d) part makes sure that the string starts with a number. ^\$? ( ( [1-9]\d {0,2} makes sure the number starts with 1 to 9.
Form validation using regex in JavaScript with Bootstrap is a script that shows how to validate form fields in your BS5 project using custom Regex. 1. Import the required Bootstrap 5 framework in your doc. 2. Create two alert element that gives Success & Error feedbacks. <!-- Alerts --> 3. Apply form validators to your HTML form.
Form Validation: Form validation is validating the values which are entered by the end-user during a form submission. For validating a form, Regular Expression plays a vital role. Let’s see what Regular Expression means. Hey geek!
Javascript Validation Numeric. We’ll start first with validating a textbox that accepts only numbers. As you can see the function validate() checks if the entered string contains characters that does NOT (notice the ^ symbol) match the numbers 0 to 9 including white spaces and special characters.
Does this do what you want?
^\d{1,3}(?:\.\d{3})*,\d{2}$
That says "1 to 3 digits, optionally followed by any number of groups of three digits preceded by a period, followed by a comma and two more digits." If you want to allow the leading whitespace present in your example, add \s*
to the front:
^\s*\d{1,3}(?:\.\d{3})*,\d{2}$
EDIT: As @ElRonnoco pointed out, the above regular expression accepts leading zeroes (e.g. 010.100,00). To disallow those, you may use this longer version:
^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0),\d{2}$
EDIT 2 The above regular expressions all match a string containing a single monetary amount and nothing else. It's not clear from the question if that's the intent.
EDIT 3 To allow numbers that have no decimal part, or only one decimal digit, change it like this:
^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$
I would give this regex a try:
\d+(?:\.\d{3})*?,\d{2}
What it says is:
- match digits until
a. a dot followed by 3 digits is found (and this step can be repeated several times)
b. or a comma followed by 2 digits is found
EDIT:
- thanks for the comments, I forgot about the constraint for the first value
updated regex
\d{1,3}(?:\.\d{3})*?,\d{2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With