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)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay