Interactive Form Elements Cheat Sheet
When filling in HTML forms, users are expected to abide by certain rules, like using numbers when asked to, or properly formatting a URL or an email. However, humans are prone to errors, and they may overlook some of the data they input. HTML form validation ensures that the data entered into each field is correctly formatted and adheres to specified constraints.
Most Common Validation Attributes
required
Denotes a mandatory input that the user can’t leave empty. It can be used with any input type like password, radio, text, and more.
<input type="text" id="firstName" name="firstName" required>
maxlength
Specifies the maximum length of a text input, preventing the user from entering more characters than the specified limit.
<input type="text" id="description" name="description" maxlength="50">
minlength
Specifies the minimum length of a text input. If set, the input will not accept fewer characters than those specified.
<input type="password" id="password" name="password" minlength="8">
min
and max
These attributes determine the minimum and maximum values allowed for an input field. They are usually applied to numerical text inputs, range inputs, or dates.
<input type="number" id="quantity" name="quantity" min="1" max="10">
<input type="range" id="volume" name="volume" min="1" max="100">
multiple
Indicates that the user can enter more than one value in a single input field. This attribute can only be used for email and file input types.
<input type="file" id="gallery" name="gallery" multiple>
pattern
Defines a particular pattern that an input field value must match to be considered valid. This attribute expects a regular expression to specify the pattern. It works with text, date, search, URL, tel, email, and password input types. For example, you can restrict phone numbers to only be from the UK.
<input type="tel" id="phone" name="phone" pattern="^(?:0|\+?44)(?:\d\s?){9,10}$">
These attributes help ensure that the data submitted via forms is valid and formatted correctly, improving user experience and data integrity.