When you need to ensure that a text input contains a valid price value, you can use jQuery to validate the field on the  keyup event.

For this example, we’ll use a simple HTML5 number type input:

We specify a  min attribute with a value of “0” so that the user may not enter in a negative number. We then specify a  step attribute with a value of “0.01” so that the user may user their up/down arrow keys to iterate the number by one hundredth at a time. We use the boolean  required attribute to require that the user enter something into this field.

Now we can also validate and format the number the user has entered with jQuery:

Initially we validate the user input with a simple regular expression to ensure that the user input was a valid price value:

Before we perform the above regular expression, we remove any period characters in the current input’s value. If the input value is invalid, we erase the character they entered. If the input value is valid, and the decimal is longer than 3 characters long, then we format the price by adding in the decimal point.

You can see an example below.

View Demo »