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



Edit in JSFiddle

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


CSS



Edit in JSFiddle

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



Edit in JSFiddle

That’s all about restricting an HTML input text box to allow only numeric values.