Explain Codes LogoExplain Codes Logo

How to avoid Decimal values in input type number

javascript
input-validation
javascript-features
accessibility
Alex KataevbyAlex Kataev·Sep 2, 2024
TLDR

Ensure integer-only input by setting <input>'s step to 1 and discarding decimals via the oninput event:

<input type="number" step="1" oninput="this.value = ~~this.value;">

This technique sets the <input> to only admit whole numbers, instantly discarding any attempted decimal input.

Going beyond the basics

A simple input constraint is the first line of defense against unwanted decimals. The application of JavaScript's bitwise operator ~~ here duplicates the functionality of a trunc() function, efficiently eliminating decimal entries. Let's probe deeper to devise more comprehensive solutions.

Establishing numeric input patterns

Utilizing a pattern attribute with a specific regular expression can guide input expectations:

<input type="number" pattern="[0-9]+" title="Numbers only">

The pattern attribute set to "[0-9]+" restricts input to numeric characters only, and the title provides additional direction, telling users: "Alright, folks! Numbers only, please!"

Putting the brakes on decimal input

A tidy JavaScript approach to block users from entering a decimal point involves capturing the onkeydown event:

function blockDecimal(e) { //if it's not a number, deny it. Ironically, '.' is a no-go here. return !(e.key === '.'); }
<input type="number" onkeydown="return blockDecimal(event)">

Translation: "Imma let you finish, but no decimals!"

Guiding user input

Providing clear and immediate feedback is a pillar of intuitive design. Consider implementing JavaScript validation functions that offer immediate input correction or guidance when users attempt to enter decimals.

A nod for accessibility

Notably, it's important to keep the type="number" attribute. Although it gives us some validation headaches, it's crucial for accessibility. Screen readers work better with explicit input types. It's the internet equivalent of keeping public spaces wheelchair-accessible.

Thinking about user flow

Remember, real-time input filtering can be a tricky beast. Make sure it doesn't scare your users away. Good user interfaces should be like smooth jazz, flowing seamlessly without any be-bop interruptions.

Handling pasting scenarios

Handling the onpaste event is often overlooked. A well-rounded solution doesn't just slap a band-aid on, it covers all bases. Ensure you strip out non-numeric characters from pasted content as well:

function filterPaste(e) { e.preventDefault(); var text = (e.originalEvent || e).clipboardData.getData('text/plain'); document.execCommand('insertText', false, text.replace(/\D/g, '')); }
<input type="number" onpaste="filterPaste(event)">

Pasting shall pass, but only if it's whole numbers!

Making room for negatives

Negatives need love too! If you wish to include negative integers, include the "-" sign in your validation:

<input type="number" oninput="this.value = this.value.replace(/[^0-9\-]/g, '');">

Setting this 'negative unless proven otherwise' atmosphere accepts negative values, extending your application use cases.