Categories
JavaScript Answers

How to Validate Floats and Decimal Separators with the HTML5 Number Input?

Spread the love

Sometimes, we want to validate floating-point numbers with decimal separators with the HTML5 number input.

In this article, we’ll look at how to validate floats and decimal separators with HTML5 number input.

Add the pattern Attribute

We can add the pattern attribute to an HTML5 number input to add validation to the input.

For instance, we can write:

<input type="number" name="price" pattern="[0-9]+([.,][0-9]+)?" step="0.01" >

Then we can write the following JavaScript code to get the value when we’re done typing on the input and move focus away from the input:

const input = document.querySelector('input')
input.addEventListener('change', (e) => {
  console.log(e.target.value)
})

The pattern attribute will restrict the value that’s entered along with the number input type.

And in the JavaScript code, we call addEventListener to listen to the change event which is triggered when we stop typing and move focus away from the input.

We get the value entered into the input with e.target.input .

Conclusion

We can add the pattern attribute to an HTML5 number input to add validation to the input.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *