Bookmark
All Settings
Theme
Font Type
Font Size
The default resizer setting is 1 or 1.0.
Text to Speech
The default Speed and Pitch settings are 1 or 1.0.
Setting Default
This action can delete all settings data, themes, text-to-speech preferences, font types, bookmarks, and even browsing history.
Chat WhatsApp

How to Limit Input Number Using JavaScript

Complete guide on how to limit the number of characters in an input number using JavaScript.
Limit Number Input with JavaScript
Source: jejaknesia.com

www.jejaknesia.com – Have you ever created a form on a website and found users entering numbers that are too long, causing the layout to break? A simple issue like this can actually have a big impact on data validation and form aesthetics. In this article, we will discuss how to limit the number of characters in a number input using a combination of HTML and JavaScript in an easy, effective, and neat way.

Why Is It Necessary to Limit the Number of Characters?

Imagine creating a registration form that asks users to enter a phone number or verification code. If the input is not limited, users could type excessive numbers, like 9999999999999999. This not only disrupts the layout but also makes the data difficult to validate.

By limiting the number of characters in the <input type="number"> element, you can:

  • Maintain consistent data format.
  • Prevent unnecessary excessive input.
  • Ensure the accuracy of incoming data.
  • Enhance form appearance and improve UX (User Experience).

1. Using HTML max and min Attributes

The simplest way to limit numeric input is by using built-in HTML attributes like max and min. However, note that these attributes only limit the value, not the number of characters.

Code Example:

<input type="number" min="0" max="999">

In the example above, users can only enter numbers between 0 and 999. However, if you want to limit the number of characters, not the value, you need a JavaScript approach.

2. Limiting Number of Characters Using JavaScript

HTML does not have a specific attribute to limit the number of characters for type="number". But you can work around this by adding an event listener in JavaScript that prevents users from typing beyond a certain limit.

Implementation Example:

<input type="number" id="limitNumber" placeholder="Enter a number" />

  const inputNumber = document.getElementById('limitNumber');
  const maxLength = 5; // Maximum 5 characters

  inputNumber.addEventListener('input', function() {
    if (this.value.length > maxLength) {
      this.value = this.value.slice(0, maxLength);
    }
  });

Explanation:

  • "input" event listener detects every time the user types something.
  • If the number of characters exceeds maxLength, the value will automatically be trimmed to fit the limit.

3. Using a Reusable Function

To be more efficient, you can create a JavaScript function that can be reused for multiple elements at once.

Flexible Function Example:

<input type="number" id="phoneNumber" placeholder="Phone Number" />
<input type="number" id="otpCode" placeholder="OTP Code" />

function limitInputLength(elementId, maxLength) {
  const el = document.getElementById(elementId);
  el.addEventListener('input', function() {
    if (this.value.length > maxLength) {
      this.value = this.value.slice(0, maxLength);
    }
  });
}

// Execute function
limitInputLength('phoneNumber', 12);
limitInputLength('otpCode', 6);

This way, you can control multiple number inputs simultaneously with a single simple function. This is very useful in large-scale projects or complex forms.

4. Combining Character Count and Value

The best approach is to combine both methods. Example:

<input type="number" id="age" maxlength="3" min="1" max="120" placeholder="Enter Age" />

maxlength is for characters while min max is for the value. Numbers outside the range 1–120 cannot be entered.


const input = document.getElementById('age');
const min = parseInt(input.min);
const max = parseInt(input.max);

input.addEventListener('input', function() {
  let val = parseInt(this.value);

  // If not a number, clear input
  if (isNaN(val)) {
    this.value = '';
    return;
  }

  // Limit value
  if (val < min) this.value = min;
  if (val > max) this.value = max;
});

This ensures that users cannot enter more than 3 digits while staying within the range 1–120.

Additional Tips for Optimal Validation
  • Use the required attribute so the form cannot be submitted before filling out.
  • Add error messages using CSS or alerts if the input is incorrect.
  • Use regex patterns if more complex validation is needed (e.g., phone numbers in a specific format).

Limiting the number of characters in number inputs is crucial for maintaining data quality and accuracy. With a simple combination of HTML and JavaScript, you can make forms more professional, clean, and user-friendly.

Start applying this practice in your projects, especially when working with numeric data such as phone numbers, verification codes, or customer IDs. Remember, small validation can save you from big mistakes!