Explain Codes LogoExplain Codes Logo

Html5 input for money/currency

html
responsive-design
best-practices
javascript
Anton ShumikhinbyAnton Shumikhin·Feb 22, 2025
TLDR

For currency inputs, use:

<input type="text" pattern="^\d*(\.\d{0,2})?$" placeholder="0.00" title="Currency (like 123.45, not three fiddy)" />

The pattern attribute here (paired with some smart regex), ensures two decimal places and validates the input, enforcing correctness without the need for JavaScript.

Diving deeper into HTML forms for currency inputs

1. Selecting an appropriate input type for currency

The HTML type="currency" does not exist. However, using type="number" and adding the step attribute with a value of 0.01, we achieve currency-like precision. For complex formats or customization, consider JavaScript solutions or certain libraries:

<input type="number" step="0.01" min="0" max="10000" placeholder="0.00" /> <!-- Fo' shizzle, no millesimal fraction pennies here! -->

You can use CSS to spruce up those input fields, and visually sneak in currency symbols without compromising your data's cleanliness for backend processing.

2. Driving accessibility & ensuring browser consistency

It's important to follow accessibility best practices for form inputs and provide clear instructions to users. Moreover, check your inputs across various browsers to ensure consistent behavior and validation.

3. Implementing advanced formatting techniques with JavaScript

To step up your HTML game, combine with JavaScript for dynamic currency symbols and on-the-fly validation. Listen to focus and blur events and toggle between formatted and raw input views accordingly.

element.addEventListener('focus', ...); // Ready to absorb some raw data! element.addEventListener('blur', ...); // Time to prettify this input!

For autolocalizaton of currencies, Number.prototype.toLocaleString can be your best friend.

Rolling out robust currency fields

1. Navigating multiple currencies

Multiple currencies are no longer an issue with the use of ISO currency codes. Include a feature to switch contexts and formatting rules accordingly.

2. Setting up server-side safety nets

Regardless of how tight your client-side validation is, server-side validation should be implemented, ensuring received numeric data aligns with expectations and stays safe from malformed data.

3. Utilizing libraries and frameworks

Here's a small shoutout to libraries and frameworks that offer a helping hand with currency input: