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:
- We select the input element with the id numericInput.
- We add an event listener to the input element to capture user input.
- 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:
- We use the type=number attribute to create a numeric input field.
- 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
Allow only numbers and decimal in textbox JavaScript regex
0
In this article, you will learn how to use JavaScript and regular expressions to restrict…
asked
Apu
0 answers
2915
In this article, you will learn how to use JavaScript and regular expressions to restrict…
Answer Link
answered
Apu