HTML5 > Forms Elements

Validate number in HTML5

How to force user to enter number only in the TextBox in HTML5?

To force user to enter only number in the Text box, we can set the type attribute of the input element to “number”.

       Number : <input type="number" name="myNumber1" id="myNumber1" required />

In case user enters some text that is not a number, the textbox value is treated as empty (in the Opera Browser).


Validating number with Step value

We can also specify a step value to this element so that it forces user to enter the value multiple of that.

<input type="number" name="myNumber1" id="Number1" step="4" />

Notice the step attribute whose value is 4. Above code will only allow user to enter the number that is multiple of 4, eg. 4, 8, 12 etc.


Specifying Max and Min value

To restrict maximum and minimum value that can be entered into the text box, we can set max and min attributes.

        <input type="number" name="myNumber" id="myNumber" min="1" max="10" />

Above code snippet allows value between 1 to 10 in the textbox.


 Views: 776 | Post Order: 93

Write for us