DEV Community

Nuttee
Nuttee

Posted on

Enhancing User Input Validation: Ensuring Proper Decimal Formatting with Regular Expressions

Because the user must pass a string of numbers, I must use regex to validate the input to ensure proper decimal format.

Example values and results.

Input result
"2" ✅
"2.3" ✅
"2.35" ✅
"2.357" ❌
1 ❌
1.0 ❌
1.325 ❌
"a" ❌
"1." ❌
"1.a" ❌
"" ❌

So the regex should be

~r/^\d+(\.\d{1,2})?$/
Enter fullscreen mode Exit fullscreen mode

Here's the breakdown of the updated pattern:

  • ^: Start of the string.
  • \d+: One or more digits (0-9).
  • (.\d{1,2})?: This part is optional, denoted by the ? at the end. If there is a decimal point ., it must be followed by 1 to 2 digits (\d{1,2}). Now, the input requires at least one digit after the decimal point.
  • $: End of the string.

This pattern will only match valid strings with one or more digits before the decimal point and, if a decimal point is present, at least one digit after it.

Top comments (0)