Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #HowTo #Html

Allow only numbers and decimal in textbox JavaScript regex

In this article, you will learn how to use JavaScript and regular expressions to restrict a textbox input to allow only numbers and decimal values.

We will explore two methods to achieve this, ensuring that your input field remains numeric and decimal-only, preventing any unwanted characters.

Using JavaScript and Regular Expressions

To begin, we will create a regex pattern that matches numeric and decimal input.

<input type="text" id="numericInput">
<script>
  const numericInput = document.getElementById("numericInput");
  numericInput.addEventListener("input", function () {
    this.value = this.value.replace(/[^0-9.]/g, "");
  });
</script>

Explanation of the above example:

  1. We select the input element with the id numericInput.
  2. We add an event listener to the input element to capture user input.
  3. The regex pattern /[^0-9.]/g allows only digits (0-9) and the decimal point (.) and replaces any other characters with an empty string.

Utilizing HTML Input Type Attribute

Another approach is to leverage the HTML input type attribute to ensure numeric and decimal input.

<input type="number" step="0.01">

Explanation:

  1. We use the type=number attribute to create a numeric input field.
  2. The step=0.01 attribute allows input with up to two decimal places.

Conclusion:

In this article, you learned two methods to restrict a textbox to accept only numbers and decimal values. By using JavaScript and regular expressions or the HTML input type attribute.

save
listen
AI Answer
Write Your Answer
loading
back
View All