Skip to the page content

Input validation

Ways to check what people type, from password rules and card numbers to server checks and an error summary.

16 cards

Validation states

The same classes and attributes on every kind of control: default with help, valid, invalid, warning and disabled, on inputs, selects, input groups and checkboxes. Each state pairs its color with an icon and words, so it reads the same without color.

Form-level

Default with help

Most teams offer 2 or 4 hours.

Valid

10% off your first order

Invalid

A ZIP code has five digits.

Warning, still allowed

kg

Over 5 kg ships as freight.

Invalid select

Pick the kind of visit.

Invalid input group

$

Price has to be above zero.

Invalid checkbox

Accept the terms to open an account.

Disabled

Set once, when the account was created.

Show code
<label class="form-label" for="zip">ZIP code</label>
<input class="form-control is-invalid" id="zip" aria-invalid="true" aria-describedby="zip-error">
<p class="val-error" id="zip-error">A ZIP code has five digits.</p>

<!-- A warning leaves the field usable -->
<div class="input-group val-is-warning">…</div>
<p class="val-warn" id="weight-note"><i class="bi bi-exclamation-triangle"></i>Over 5 kg ships as freight.</p>

Email with typo suggestion

An email input that checks the format when you leave it, then compares the domain with common providers. One or two letters off, or a mistyped ending like .con, and it offers the fix. The suggestion never blocks saving.

Email

Try or .

Show code
const common = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'icloud.com'];
function suggest(email) {
  const [user, domain] = email.toLowerCase().split('@');
  const near = common.find((d) => d !== domain && distance(d, domain) <= 2);
  return near ? `${user}@${near}` : null;
}
// distance() is a plain Levenshtein edit count, about ten lines.

Password with strength meter

For setting a new password. A show/hide toggle, a four-step meter and a rule list that checks off as you type. The confirm field waits until it is as long as the first before it says anything.

Password

The password can't contain the name in this address.

Start typing to see how strong it is

  • At least 10 characters
  • Upper and lower case letters
  • A number or a symbol
  • Doesn't contain "elaine" or "zeller"

Show code
const rules = {
  length: (v) => v.length >= 10,
  case:   (v) => /[a-z]/.test(v) && /[A-Z]/.test(v),
  digit:  (v) => /[\d\W_]/.test(v),
  name:   (v) => !/elaine|zeller/i.test(v)
};
input.addEventListener('input', () => {
  const met = Object.keys(rules).filter((k) => rules[k](input.value));
  items.forEach((li) => li.classList.toggle('is-met', met.includes(li.dataset.valRule)));
  meter.dataset.level = input.value ? Math.max(1, met.length) : 0;
});

Stepper with step and a linked rule

A number stepper reads min, max and step from its input and clamps anything typed. It can warn at a value that is allowed, or follow a rule set by another field: a weekly reorder needs two units, and the error offers both fixes.

Number

Step 5, from 0 to 995. Warns at 0.

Reorder every

Pick Week with 1 unit to see the rule.

Show code
<input type="number" class="basalt-stepper-input" min="0" max="995" step="5">

// Re-check the pair whenever either side changes.
form.addEventListener('change', checkPair);
function checkPair() {
  const weekly = form.elements.valSubEvery.value === 'week';
  if (weekly && +units.value < 2) {
    return showError(crossMsg, 'A weekly reorder starts at 2 units.', ['Make it 2 units', 'Every 2 weeks instead']);
  }
  return clearError(crossMsg);
}

Currency input with a comparison rule

A decimal input with a currency prefix. Only digits and one decimal point get in, with two decimals at most. A second amount can be checked against the first: here the sale price has to be lower, and the saving shows once it is.

Number
$

$

Leave empty for no sale.

Show code
const MONEY = /^\d+(\.\d{1,2})?$/;
function checkSale() {
  if (!sale.value) return ok(sale);
  if (!MONEY.test(sale.value)) return fail(sale, 'Numbers only, like 15.00.');
  if (+sale.value >= +price.value) return fail(sale, 'A sale price has to be lower than $' + price.value + '.');
  note.textContent = Math.round((1 - sale.value / price.value) * 100) + '% less';
  return ok(sale);
}
price.addEventListener('input', () => { if (sale.value) checkSale(); });

Date with blocked days

A native date input with min and max set, so the picker grays out days outside the window. Rules the browser can't express, like no Sundays, are checked on change, and the error suggests the nearest days that work.

Date

At least two days from today, within three months, Monday to Saturday.

Show code
date.min = iso(addDays(today, 2));
date.max = iso(addDays(today, 92));
date.addEventListener('change', () => {
  const d = parse(date.value);
  if (d.getDay() === 0) return fail(date, `Crews don't work on Sundays. Try ${day(addDays(d, -1))} or ${day(addDays(d, 1))}.`);
  pass(date);
});

Phone number

A tel input that formats a US number as (512) 555-0142 while you type and brings up the number pad on phones. It accepts a leading 1, then checks for ten digits and an area code that can exist. Optional, so empty is fine.

Masked

US numbers, ten digits.

Show code
phone.addEventListener('input', (e) => {
  if (e.inputType?.startsWith('delete')) return;   // let Backspace through
  let d = phone.value.replace(/\D/g, '').slice(0, 11);
  if (d.length === 11 && d[0] === '1') d = d.slice(1);
  phone.value = d.length > 6 ? `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6, 10)}`
    : d.length > 3 ? `(${d.slice(0, 3)}) ${d.slice(3)}` : d;
});
// On blur: ten digits, and the area code can't start with 0 or 1.

Card number, expiry and security code

Masked payment inputs. The card number groups its digits, shows the brand and runs a Luhn check. Expiry adds the slash and refuses past months. The security code wants 4 digits for Amex and 3 for the rest.

Masked

Test card: 4242 4242 4242 4242, or 3782 822463 10005 for Amex.

Show code
card.addEventListener('input', () => {
  const n = card.value.replace(/\D/g, '');
  const amex = /^3[47]/.test(n);
  const cut = n.slice(0, amex ? 15 : 16);
  card.value = (amex ? [cut.slice(0, 4), cut.slice(4, 10), cut.slice(10)] : cut.match(/.{1,4}/g) || [])
    .filter(Boolean).join(' ');
});
const luhn = (n) => [...n].reverse().reduce((sum, d, i) =>
  sum + (i % 2 ? (d * 2 > 9 ? d * 2 - 9 : d * 2) : +d), 0) % 10 === 0;

Pattern input with auto-format

For codes with a fixed shape, like shop stock SKUs or reference numbers. It uppercases and turns spaces into hyphens as you type, then checks the value against the pattern when you leave the field.

Pattern

Item, maker, size. Try typing "card lmh 1620".

Show code
const SKU = /^[A-Z]{3,4}-[A-Z]{3}-\d{2,4}$/;
sku.addEventListener('input', () => {
  const at = sku.selectionStart;
  sku.value = sku.value.toUpperCase().replace(/\s+/g, '-');
  sku.setSelectionRange(at, at);
});
sku.addEventListener('blur', () =>
  SKU.test(sku.value) ? pass(sku) : fail(sku, 'Use ITEM-MAKER-SIZE, like CARD-LMH-1620.'));

Postal code by country

A postal code input whose label, example and pattern follow the country: five digits for the US and Germany, letters and digits for the UK and Canada. Changing the country re-checks what is already typed.

Pattern

Five digits, or ZIP+4 like 78701-1234.

Show code
const POST = {
  US: { label: 'ZIP code',    re: /^\d{5}(-\d{4})?$/ },
  GB: { label: 'Postcode',    re: /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i },
  DE: { label: 'Postal code', re: /^\d{5}$/ },
  CA: { label: 'Postal code', re: /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/i }
};
country.addEventListener('change', () => {
  label.textContent = POST[country.value].label;
  if (post.value) check(post);
});

Textarea with character counter

For text with a hard limit. The counter warns 20 characters out and turns into an error past the limit, so nothing is cut off silently. An emoji counts as one character, and the field can refuse ones it can't print.

Textarea
0 / 150

Show code
const LIMIT = 150, WARN_AT = 130;
note.addEventListener('input', () => {
  const n = [...note.value].length;      // counts emoji as one character
  count.textContent = n > LIMIT ? `${n - LIMIT} over the limit` : `${n} / ${LIMIT}`;
  counter.dataset.state = n > LIMIT ? 'over' : n >= WARN_AT ? 'near' : '';
  if (/\p{Extended_Pictographic}/u.test(note.value)) fail(note, "The card printer can't print emoji.");
});

Tag input with a limit

A list of short values in one field. Enter adds a tag and Backspace on an empty field removes the last. It stops at a set number, names a duplicate instead of adding it, and can require at least one.

Tags
Dementia care First aid
Up to five. Try adding First aid again.

Show code
<div class="basalt-tags" data-basalt-tags data-max="5">
  <input class="basalt-tags-input" id="skills" aria-describedby="skills-error">
</div>

box.addEventListener('basalt:tags-duplicate', (e) => fail(input, `"${e.detail.value}" is already listed.`));
form.addEventListener('submit', () => {
  if (!box.basaltTags.get().length) fail(input, 'Add at least one skill.');
});

Availability check

For usernames, booking page addresses and slugs. The format is checked on every key, and the server is asked once typing stops for half a second. A taken value comes back with free alternatives.

Server-checked
fieldline.app/

3 to 24 lowercase letters, numbers or hyphens. Try or , both taken.

Customers will visit fieldline.app/your-company

Show code
let timer, lastAsked;
input.addEventListener('input', () => {
  clearTimeout(timer);
  if (!/^[a-z0-9](?:[a-z0-9-]{1,22}[a-z0-9])$/.test(input.value)) return showFormatError();
  status.textContent = 'Checking…';
  timer = setTimeout(async () => {
    const asked = lastAsked = input.value;
    const { free, suggestions } = await api.checkHandle(asked);
    if (asked !== lastAsked) return;   // an older answer arrived late
    free ? showFree() : showTaken(suggestions);
  }, 500);
});

Code checked by the server

For values only the server can judge, like discount or gift codes. The input uppercases what you type, the button shows a spinner while it waits, and a refusal names the reason instead of a bare "invalid".

Server-checked

Try , , or .

  • Bar Loafers$790.00
  • Shield Sunglasses$520.00
  • Shipping$14.95

Total$112.95

Show code
button.disabled = true; form.setAttribute('aria-busy', 'true');
const res = await fetch('/api/discounts/check', { method: 'POST', body: JSON.stringify({ code, cartId }) });
const { ok, reason, amount } = await res.json();
// reason: 'unknown' | 'expired' | 'minimum' | 'category'
ok ? applyDiscount(amount) : fail(input, messages[reason]);
button.disabled = false; form.removeAttribute('aria-busy');

Native constraints and ValidityState

What the browser checks on its own from type, required, pattern and minlength. Pick an input type, type into it and watch its ValidityState flags and the message the browser would show.

Form-level
Input type

type="email" required

  • valueMissing
  • typeMismatch
  • patternMismatch
  • tooShort
  • tooLong
  • valid
validationMessage

Show code
input.addEventListener('input', () => {
  const v = input.validity;              // a live ValidityState
  flags.forEach((li) => li.classList.toggle('is-on', v[li.dataset.flag]));
  message.textContent = input.validationMessage || 'Nothing to report';
});
// Swap the browser's wording for your own:
input.setCustomValidity(v.patternMismatch ? 'Use FL- and five digits.' : '');

Error summary

For longer forms. Each field checks itself when you leave it and clears as soon as it is right. Submitting with gaps lists every problem at the top, each one a link to its field, and the list shrinks as you fix them.

Form-level

Show code
// Check a field when it is left, then again on every keystroke once it has an error.
input.addEventListener('blur', () => check(input));
input.addEventListener('input', () => { if (input.getAttribute('aria-invalid') === 'true') check(input); });

form.addEventListener('submit', (e) => {
  e.preventDefault();
  const problems = fields.filter((f) => !check(f));
  if (problems.length) {
    list.innerHTML = problems.map((f) => `<li><a href="#${f.id}">${message(f)}</a></li>`).join('');
    summary.hidden = false;
    summary.focus();
  }
});