DEV Community

Nuttee
Nuttee

Posted on

1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay