How to allow only numbers and decimal points in an HTML input element?

How can you make an HTML input element that allows only numbers and amounts to be entered?

Are you collecting amounts on your web page such as prices ($12.34), distances (1.5 miles) or lengths (22.3 cm), temperature (70.4 C) or duration (19.72 seconds)?

Do you need to make your input element reject all characters except for the ten digits and the decimal point?

Do you find that users are often entering these numbers in the wrong way (using a comma, including the dollar sign or unit, including spaces, or writing some text that they mean for a different input field)? Is this causing them grief since, after filling out the form and submitting it, they are informed of the error, they have to tediously locate the error field, correct it and resubmit the form?

Here is a quick and easy way to solve this problem for good — in many if not most cases!

Let’s start with the most simplest text field that one can place in an HTML page. As you’re probably aware, such an HTML element is called “input”, for example:

<form action="/process_form.cgi">
  <input type="text" name="amount">
  <input type="submit">

And your visitors can then put in any value whatsoever, even if they must enter a number! While you can validate this in your CGI script or other code on the server (what the “action” tag of the form corresponds to), when the user did not enter proper values they will not be happy to discover they made a “mistake”, and they may even abandon your website for good!

Therefore it is a good idea to make sure that your users understand what is asked, and get immediate feedback about how they are filling out the form. Here they should enter numbers, not names or addresses or anything else but numbers!

Here is the simple solution: change the type from “text” to “number.” This can be done with HTML 5, and so there you go!

<form action="/process_form.cgi">
  <input type="number" name="amount">
  <input type="submit">

WIth this, the user can enter digits, decimal point and a dash (for negative numbers) as required. But they cannot enter letters, or symbols, not even through copy-and-paste. What’s more, they are alerted to the requirement with popup hints. And: you don’t need to worry about WCAG, accessibility, and screenreaders — you can rely on them to make this work without anything else!

Reminder: HTML 5 means you need to use this DOCTYPE at the beginning of your HTML document:

<!DOCTYPE html>

You can read about additional options for the input type at its W3C page

Comments on this post

No comments.

Leave a Reply

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

Trackbacks and Pinbacks on this post

No trackbacks.

TrackBack URL