Published
November 23, 2022
Updated
In HTML5, form Input fields have a number of built-in validation features, such as;
- The input type
- The required status
- Regex validation patterns
When these validation rules are specified, and the form data does not meet their criteria,
Field Validation
Input type
The input type indicates the type of data expected, and is a good first-line-of-defense. On some browsers- particularly mobile browsers- it will also change the UI/UX of that input to work best for that device.
<input type="email" name="email">
<input type="url" name="website">
<input type="number" name="age">
Required status
Ensures that a field is not left empty.
<input type="text" name="username" required>
Regex validation patterns
Offers a much more complex pattern-matching approach. Regex syntax is very picky and can be difficult to code and debug, but a good regex is hugely helpful in validating your inputs.
<input type="text" name="zipcode" pattern="\d{5}" title="Enter a 5-digit zip code">
Length Constraints
- Attributes:
maxlength
,minlength
- Enforces constraints on the number of characters in a text field.
<input type="text" name="username" minlength="3" maxlength="15">
Value Range
- Attributes:
min
,max
,step
- Used with inputs of type
number
,date
,time
, etc., to define permissible ranges and steps.
<input type="number" name="quantity" min="1" max="10" step="1">
<input type="date" name="dob" min="1900-01-01" max="2023-12-31">
Specific Form Input Types
Checkbox/Radio Button Group
- Ensures at least one checkbox or radio button is selected when combined with
required
.
<input type="radio" name="gender" value="male" required> Male
<input type="radio" name="gender" value="female"> Female
File Input Validation
- Attributes:
accept
- Restricts the type of files that can be uploaded.
<input type="file" name="profile-picture" accept="image/*">
Multiple Input Values
- Attribute:
multiple
- Allows entering multiple values, typically for
email
orfile
inputs.
<input type="email" name="emails" multiple>
Validation Controls
Form-Level Validation
Enable-disable form validation;
<form novalidate>
Browser Feedback Mechanisms
- Default Tooltips: Browsers display tooltips with error messages when validation fails.
- Custom messages for certain validation attributes can be set using the
title
attribute.
CSS Pseudo-Classes:
:valid
and:invalid
can style fields based on validation state.
input:invalid {
border: 2px solid red;
}
input:valid {
border: 2px solid green;
}
FAQs
Answers to frequently asked questions.