Explain Codes LogoExplain Codes Logo

How to allow only numeric (0-9) in HTML inputbox using jQuery?

javascript
input-validation
client-side-validation
server-side-validation
Alex KataevbyAlex Kataev·Nov 8, 2024
TLDR

Establish numeric-only fields using jQuery's .keydown(), registering both key codes for numbers and essentials like backspace and navigation arrows. Below is the code:

$('input[type="text"]').keydown(function(e) { // Numbers, control keys: backspace, delete, arrows - the numbers party VIPs! var validKeys = [8, 9, 13, 27, 35, 36, 37, 38, 39, 40, 46, 48, 57, 96, 105]; var isCommand = e.metaKey || e.ctrlKey; var isNumber = (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105); if ($.inArray(e.keyCode, validKeys) !== -1 || isCommand || isNumber) return; // Admit entry e.preventDefault(); // Deny stroking of non-numeric keys });

Just append to your input, and it halts non-numeric keystrokes while permitting basic navigation.

Taking care of edge cases

Allowing decimal points and control keys

In some scenarios, numbers are not solely integers. To allow decimal points, accommodate the keycodes 110 and 190:

$('input[type="text"]').keydown(function(e) { var validKeys = [8, 9, 13, 27, 35, 36, 37, 38, 39, 40, 46, 48, 57, 96, 105, 110, 190]; //... rest of the logic as above ... });

Simultaneously, pay attention to ctrlKey for key combinations, ensuring a smooth user experience:

$('input[type="text"]').keydown(function(e) { //...validKeys as above... var ctrlCmdKeys = [65, 67, 86, 88]; // A, C, V, X for Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X if (e.ctrlKey && ctrlCmdKeys.includes(e.keyCode)) { return; // Allow clipboard actions } // ... rest of the logic as above ... });

Combining client-side and server-side validation

Client-side validation is always handy, but it's imperative to perform server-side validation for enhanced security because client scripts may be overridden:

app.post('/data/submit', function(req, res) { var numericInput = req.body.numericField; if (/^\d+$/.test(numericInput)) { // Proceed with safe, numeric input } else { // Handle invalid input res.status(400).send('Invalid input'); } });

Handling mobile irregularities

HTML5 number inputs may behave differently with mobile browsers. Take into account the potential issues with attributes like step, min, max, and virtual keyboards:

<input type="text" name="numberField" pattern="\d*" /> <!-- Forces numeric keypad on iOS -->

Providing feedback, gracefully

Styling for invalid entries

To provide visual feedback to users, apply an input-error class when the input is non-numeric. Customize it to align with your site's aesthetics:

$('input').on('input', function() { if (!/^\d*$/.test(this.value)) { $(this).addClass('input-error'); // Add class if error } else { $(this).removeClass('input-error'); // Remove if corrected } });

Add your style preference to .input-error in your CSS:

.input-error { border-color: red; background-color: #ffcccc; }

Preserving cursor position

Ensure the user's cursor and selection are undisturbed during the input filtering process:

$('input').on('input', function() { var start = this.selectionStart; var end = this.selectionEnd; this.value = this.value.replace(/[^0-9]/g, ''); this.setSelectionRange(start, end); });