Explain Codes LogoExplain Codes Logo

Allow 2 decimal places in <input type="number">

html
frontend-validation
input-formatting
user-experience
Alex KataevbyAlex Kataev·Oct 20, 2024
TLDR

Achieve 2 decimal places with step="0.01" and use a pattern to validate the format:

<input type="number" step="0.01" pattern="^\d+(\.\d{0,2})?$" title="Max 2 decimal places.">

Never forget: server-side validation is crucial for data integrity.

Non-regex precision control

Let's limit user's input to two decimal places without regex:

<input type="number" step="0.01" min="0">

Now increments of step="0.01" are allowed. Additionally, "negative numbers" are blocked by min="0", making it excellent for price fields.

Catching user mistakes on the fly

To improve user experience (UX) provide instantaneous feedback. Use JavaScript's onchange or onblur events:

document.querySelector('input[type="number"]').onblur = function(e) { // Don't worry, keep the change. e.target.value = parseFloat(e.target.value).toFixed(2); };

This ensures users will always see their input formatted post-haste, right after exiting the input field.

Plan B: When HTML5 features fail

In cases when HTML5 features are unsupported, an input type="text" plus JavaScript formatting ensures a uniform user experience:

<input type="text" id="price" onchange="formatDecimal(this)">
function formatDecimal(input) { // "I'm just a penny-ante function, but I keep things precise." let value = parseFloat(input.value).toFixed(2); input.value = value; }

At the expense of not using input type="number", we still manage to control decimal places.

Putting the user first: Frontend strategies

Frontend validation is a boon to UX and form interaction. Let's see a few strategies:

  • Posh up those inputs using class="form-control".
  • Mark input fields as required to ensure users don't forget any crucial data.
  • Bring in jQuery's blur handler for effective input formatting:
$('.form-control').blur(function() { // Little known fact: jQuery also doubles as a barber. Just gave you a trim! this.value = parseFloat(this.value).toFixed(2); });

Still, don't overlook your security measures. Server-side validation remains your ultimate guard against threats.

Balancing act: HTML5 and JavaScript

HTML5 provides step, min, and pattern, boosting client-side validation. Meanwhile, JavaScript employs dynamic behaviors like toFixed(2) for consistent two-decimal precision.

Stay safe: Prioritize Security

No matter the robustness of your frontend fortifications, always consider server-side validation as an unshakeable pillar of security.

Future-proofing your code

Keep your application ready for future HTML5 updates, but remember to empathize with legacy browsers. Safe measures like providing fallbacks ensure step attribute's reliability.