Open In App

How to specify the legal number intervals for an input field in HTML5 ?

Last Updated : 01 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we learn how to set the legal number intervals in the input field. This helps the user to enter numbers that follow the given interval and disallows any other value during validation. 

We have to use the step attribute of the <input> element to set up the legal intervals in the input field. We will first create a form that contains the input area and set its step attribute to the value required. The validation of the field would automatically take place when the user tries to submit the form by showing an error.

Syntax:

<input type="number" step="value">

Example: In this example, the step attribute is set to 4, therefore a user is allowed to enter values that are in steps of 4.

HTML




<html>
 
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
    <form action="/">
        <label for="score">
            <b>Score:</b>
        </label>
        <input type="number"
               name="score"
               id="score"
               step="4">
        <br><br>
        <button type="submit">
            Continue
        </button>
    </form>
</body>
</html>


Output:

In the above example, we have taken step=4 then we can add only -4,0,4,8 etc. These are the only legal number. We cannot add 3,-3 because they are not legal numbers. The step attribute also works with the max & min attribute for creating the legal range.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads