How to disable input of any characters except 0 and positive numbers in html input

To restrict input in an HTML <input> field to allow only digits (0 and positive numbers), you can use several approaches.

1. Using the type="number" Attribute

HTML provides a built-in type for numbers:

<input type="number" min="0" oninput="validity.valid || (value='');" />
  • The min="0" attribute prevents negative numbers from being entered.
  • The oninput event resets the field if invalid characters (e.g., letters) are entered.

Drawback: Users can bypass this restriction using developer tools.

2. Adding a Restriction Using pattern (Regular Expression)

You can use the pattern attribute:

<input type="text" pattern="^[0-9]*$" title="Enter only a positive number or 0" />
  • pattern="^[0-9]*$" allows only digits (0–9).
  • The title attribute provides a hint if the user enters invalid characters.

3. JavaScript for Dynamic Validation

If stricter control is needed (e.g., to prevent typing invalid characters), use JavaScript:

<input type="text" id="numberInput" />

<script>
  const input = document.getElementById('numberInput');

  input.addEventListener('input', () => {
    input.value = input.value.replace(/[^0-9]/g, ''); // Removes everything except digits
  });
</script>

4. Combining Methods

You can combine the above methods for enhanced restriction:

<input 
  type="text" 
  pattern="^[0-9]*$" 
  title="Enter only a positive number or 0" 
  oninput="this.value = this.value.replace(/[^0-9]/g, '');"
/>

The most versatile and reliable approach is to combine the pattern or type="number" attributes with JavaScript for dynamic input handling.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more