Sub topic 4
Input types that validate for you
This chapter assumes you know how a form control's name and value reach the server, the basic constraint attributes (required, min, max, pattern), and how to attach an event listener in JavaScript. The type attribute on an <input> does more than change its appearance. For several types, the browser also checks the value against a format and reports a failure through the same validation system you saw with the constraint attributes.
What the type adds
A text input accepts any string. When you set type="email", type="url", type="number", or a date type, the browser applies three extra behaviors:
- Value sanitization. The browser cleans the value before validating it. For
email, it strips leading and trailing whitespace. Fornumber, a value that is not a valid floating-point number becomes the empty string. - A format check. If the value does not match the type's grammar, the control is invalid.
- Type-specific attributes.
min,max, andstepstart to mean something.multiplebecomes available onemail.
Most types also change the virtual keyboard on phones, which helps users but does not validate anything.
The checks follow one order. The diagram shows what happens to a value on a type that validates.
An empty value skips every format check. If you want to forbid empty input, you must add required. A field with type="email" and no required is valid when left blank.
Types and the checks they run
| Type | What the browser checks | Flag that reports failure |
|---|---|---|
| `email` | One address (or a comma-separated list with `multiple`) in the HTML spec's simplified grammar | `typeMismatch` |
| `url` | An absolute URL that includes a scheme | `typeMismatch` |
| `number` | A valid floating-point number, plus `min`, `max`, `step` | `badInput`, `rangeUnderflow`, `rangeOverflow`, `stepMismatch` |
| `date`, `time`, `month`, `week`, `datetime-local` | A real calendar or clock value, plus `min`, `max`, `step` | `badInput`, `rangeUnderflow`, `rangeOverflow`, `stepMismatch` |
| `range` | Always holds a value. The browser clamps it to `min` and `max` | None in practice |
| `color` | Always holds a valid `#rrggbb` value, `#000000` by default | None in practice |
| `tel` | Nothing. Telephone formats vary too much | Only `pattern` and length |
| `text`, `search`, `password` | Nothing | Only `pattern` and length |
The flags are properties of the control's validity object. Later chapters cover that object in detail. This chapter only names the flag that each rule sets.
Email and URL
The email type uses a deliberately loose grammar. It requires something, an @, and a hostname made of labels separated by dots. It does not require a dot in the hostname, so ann@localhost is valid, and so is ann@example. It also does not confirm the mailbox exists.
<label for="work-email">Work email</label>
<input id="work-email" name="email" type="email" required autocomplete="email">
<label for="cc">Copy these people (comma separated)</label>
<input id="cc" name="cc" type="email" multiple>With multiple, the browser splits the value on commas, trims each part, and checks every address. The submitted value is still one string.
If you need stricter rules, such as requiring a dot or limiting the domain, add a pattern. The type check and the pattern both run, and either one can fail.
<input type="email" name="email" required
pattern="[^@\s]+@[^@\s]+\.[a-z]{2,}"
title="Use an address like [email protected]">The url type requires a scheme. https://example.com/a passes, and example.com fails. Any scheme is accepted, including mailto:x and javascript:alert(1), so type="url" does not make a link safe to render. If your page later puts that value into an href, the server must check the scheme against an allow list such as http and https.
Number
type="number" is the most flexible type, and the one people misuse most.
minandmaxset an inclusive range.stepsets the allowed increments. It defaults to1, which means only whole numbers pass unless you change it.- The step base is
minif present, otherwise thevalueattribute, otherwise zero. Withmin="5" step="5", the allowed values are 5, 10, 15, and so on. step="any"turns off the step check, which is what you want for measurements with unpredictable precision.
<label for="price">Price (USD)</label>
<input id="price" name="price" type="number" min="0" step="0.01" required>
<label for="qty">Quantity</label>
<input id="qty" name="qty" type="number" min="1" max="99" step="1" value="1">A common error is leaving the default step in place for a decimal field. A user who types 19.99 into a bare type="number" input sees a message about the nearest valid values, because stepMismatch is set.
Letters typed into a number field are handled differently across browsers. Some block non-numeric keys, and some allow them. When the text cannot be parsed, the control's value is an empty string, and Chrome and Firefox set badInput. This is why a non-required number field can appear to be empty and yet be invalid.
<br>
Date and time types
The five date and time types validate that the value is a real moment. 2026-02-30 is rejected because February has no 30th day. The value format is fixed no matter how the browser displays it to the user.
| Type | Value format | Unit of `step` | Default step |
|---|---|---|---|
| `date` | `2026-11-30` | days | 1 |
| `time` | `08:30` | seconds | 60 |
| `month` | `2026-11` | months | 1 |
| `week` | `2026-W49` | weeks | 1 |
| `datetime-local` | `2026-11-30T08:30` | seconds | 60 |
The user may see 30/11/2026 or 11/30/2026 depending on locale, but your JavaScript and your server always see the ISO format. That is a good reason to parse these values and not to guess.
The step base rule works here too. If you give a date input min="2026-01-05" (a Monday) and step="7", only Mondays are valid.
<label for="meeting">Weekly meeting (Mondays only)</label>
<input id="meeting" name="meeting" type="date"
min="2026-01-05" max="2026-12-28" step="7" required>
<label for="slot">Appointment time (every 15 minutes)</label>
<input id="slot" name="slot" type="time"
min="09:00" max="17:00" step="900" required>The step for time is in seconds, so 900 means 15 minutes. If step is 60 or more and divisible by 60, most browsers hide the seconds portion of the control.
Browser support for these controls is wide, but the pickers look different on each platform. Very old browsers and some embedded views fall back to a plain text box. In that case no format check runs, so the server-side check described in a later chapter matters even more.
Types that do not validate
tel, search, password, and text have no format grammar. Do not expect type="tel" to reject letters. You must supply pattern yourself. color and range cannot be empty, so required has no effect on them, and they are always valid.
The pattern attribute works only on text, search, url, tel, email, and password. Putting pattern on a number or date input does nothing, and the browser does not warn you. The pattern must match the whole value, as if wrapped in ^(?: and )$, so you do not add anchors yourself.
Seeing which rule failed
When a field is invalid, the validity object tells you which rule failed. This page logs the failing flags as you type, so you can try each type.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Type validation explorer</title>
</head>
<body>
<form id="demo">
<label for="e">Email</label>
<input id="e" name="e" type="email">
<label for="u">URL</label>
<input id="u" name="u" type="url">
<label for="n">Amount</label>
<input id="n" name="n" type="number" min="0" max="100" step="0.5">
<label for="d">Date</label>
<input id="d" name="d" type="date" min="2026-01-01" max="2026-12-31">
</form>
<pre id="log"></pre>
<script>
const flags = [
'valueMissing', 'typeMismatch', 'patternMismatch', 'tooLong',
'tooShort', 'rangeUnderflow', 'rangeOverflow', 'stepMismatch',
'badInput', 'customError'
];
const form = document.getElementById('demo');
const log = document.getElementById('log');
form.addEventListener('input', (event) => {
const field = event.target;
if (!(field instanceof HTMLInputElement)) return;
const failed = flags.filter((flag) => field.validity[flag]);
log.textContent =
`${field.name}: value=${JSON.stringify(field.value)}\n` +
`valid=${field.validity.valid}\n` +
`failed=${failed.join(', ') || 'none'}\n` +
`message=${field.validationMessage}`;
});
</script>
</body>
</html>Try these inputs and compare the output:
ann@localhostin the email field is valid.example.comin the URL field setstypeMismatch.0.3in the amount field setsstepMismatch, because the step base is0and the step is0.5.- A date in 2027 sets
rangeOverflow.
Note that validationMessage is written by the browser, in the user's language. The next chapters show how to replace it.
Common errors
- Assuming empty means invalid. Add
requiredwhen the field is mandatory. - Using
patternonnumber. It is ignored. Usemin,max, andstep, or switch totextwithinputmode. - Forgetting
stepfor decimals. The default step of 1 rejects0.5and19.99. - Treating
type="email"as proof of a real address. It checks shape only. The only proof is sending a message. - Trusting
type="url"for safety. It accepts any scheme. - Reading dates as locale strings. The
valueis always ISO format. - Assuming the control exists. On browsers that lack a date picker, the field becomes plain text with no check.
Exercise
A form has <input type="number" name="price" min="0"> and a user enters 12.50. The browser refuses to submit and says the value is invalid. Which validity flag is set, why, and what is the smallest change that fixes it for prices in cents?
Show answer
stepMismatch is set. The default step is 1 and the step base is min (0), so only whole numbers are valid. Adding step="0.01" allows values like 12.50. Using step="any" would also stop the check, but it would allow values like 12.505 that you probably do not want.
Exercise
You add pattern="[0-9]{5}" to <input type="number" name="zip"> and find that abc is still blocked but 1234 is accepted. Explain what is happening and how you would build a five-digit ZIP code field correctly.
Show answer
pattern does not apply to type="number", so the browser ignores it. abc is blocked because it is not a parseable number (badInput), and 1234 is a valid number. Use <input type="text" name="zip" inputmode="numeric" pattern="[0-9]{5}" required> instead. This keeps leading zeros, shows a numeric keyboard, and enforces exactly five digits.