How to Use Min and Max for Validation in HTML Forms
Use the
min and max attributes on HTML input elements like number, range, date, or time to set the minimum and maximum allowed values. The browser will prevent form submission if the entered value is outside this range.Syntax
The min and max attributes define the smallest and largest values allowed for an input. They work with input types such as number, range, date, time, and datetime-local.
min: The minimum acceptable value.max: The maximum acceptable value.
Both attributes take values matching the input type format.
html
<input type="number" min="1" max="10">
Output
A number input box that only accepts values from 1 to 10.
Example
This example shows a form with a number input that only accepts values between 5 and 15. If the user enters a value outside this range, the browser will show a validation error and prevent submission.
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> <label for="age">Enter your age (5 to 15):</label> <input type="number" id="age" name="age" min="5" max="15" required> <button type="submit">Submit</button> </form> </body> </html>
Output
A form with a number input labeled 'Enter your age (5 to 15):' and a submit button. The input only accepts numbers between 5 and 15.
Common Pitfalls
- Not matching the
minandmaxvalues to the input type format (e.g., using text values for a number input). - Forgetting to add
requiredwhen you want to force input; otherwise, empty input passes validation. - Relying only on client-side validation; always validate again on the server.
- Using
minandmaxon input types that do not support them (liketext), which will have no effect.
html
<!-- Wrong: min/max on text input does nothing --> <input type="text" min="1" max="10"> <!-- Right: use number input for min/max validation --> <input type="number" min="1" max="10">
Quick Reference
| Attribute | Description | Example Value | Supported Input Types |
|---|---|---|---|
| min | Minimum allowed value | 1 | number, range, date, time, datetime-local |
| max | Maximum allowed value | 10 | number, range, date, time, datetime-local |
Key Takeaways
Use
min and max on inputs like number and date to set allowed value ranges.The browser blocks form submission if the input value is outside the min-max range.
Always pair min-max with the correct input type for validation to work.
Add
required if you want to prevent empty submissions.Client-side validation is helpful but always validate again on the server.