Restrict an HTML input text box to allow only numeric values
This post will discuss how to restrict an HTML input text box to allow only numeric values.
1. Using <input type="number">
The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values. This is demonstrated below:
HTML
|
1 2 |
<label for="salary">Enter your salary:</label> <input type="number" id="salary" name="salary"> |
2. Using pattern attribute
Alternatively, you can use the pattern attribute to specify a regular expression that should match the provided input.
The usage of the pattern attribute is demonstrated below. If the values contain non-digit characters, the element matches the :invalid CSS pseudo-classes.
HTML
|
1 2 |
<label for="salary">Enter your salary:</label> <input type="text" id="salary" name="salary" pattern="[0-9]+"> |
CSS
|
1 2 3 |
input:invalid { border: 3px solid red; } |
3. Using oninput event
Another solution is to use the oninput property to processes input events on the <input> elements. To restrict the user to enter only numeric values, you can do like:
HTML
|
1 2 3 |
<label for="salary">Enter your salary:</label> <input type="text" id="salary" name="salary" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" /> |
That’s all about restricting an HTML input text box to allow only numeric values.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)