Thursday, 23 January 2025

HTML Input Number Field: A Guide to min, max, and Validation

The type="number" attribute in the HTML <input> element is used to create an input field that allows the user to enter numerical values. This is useful when the input data is expected to be a number, such as age, quantity, or any other numerical value.

min Attribute

The min attribute specifies the minimum value that can be entered in the input field. If the user enters a value below this, it will either trigger validation or not allow the submission (depending on the form validation settings).

 

max Attribute

The max attribute sets the maximum value that can be entered. If the user tries to input a number higher than this value, it will be considered invalid.

 

min-max-number-check.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Min Max Validation Example</title>
</head>
<body>
    <form action="https://httpbin.org/post" method="POST">
        <label for="quantity">Enter a quantity (between 1 and 10):</label><br>
        <input type="number" id="quantity" name="quantity" min="1" max="10" required style="width: 40px;"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Above snippet generate below screen.


 

Use up, down arrows to select the quantity. If you insert any data that is less than 1 and greater than 10, you will get a validation error. 

 


In this example,

1.   The user is asked to enter a number between 1 and 10.

2.   The min="1" ensures the value cannot be lower than 1.

3.   The max="10" ensures the value cannot exceed 10.

4.   The required attribute makes it mandatory to fill the input.


Previous                                                    Next                                                    Home

No comments:

Post a Comment