Lesson 1 of 8

Custom validation

Goal

Add a validation rule the browser doesn't know

01

Explanation

The browser can validate emails, numbers and text length on its own, but it knows nothing about your own business rules, like "the code starts with SA" or "the quantity is a multiple of five."

When you call input.setCustomValidity('message'), the field becomes invalid and your message is attached to it. When you call setCustomValidity(''), the field is valid again. That way your rule becomes part of the browser's own validation, instead of a separate check you write next to it.

Most importantly, clear the message first every time you validate. Otherwise the field stays invalid forever after the first error.

02

Your task

Make #code valid only when it starts with SA followed by three digits.

Checks

5 checks
  1. A correct code makes the field valid
  2. A code that doesn't start with SA is rejected
  3. A code with the wrong number of digits is rejected
  4. The rejection message isn't empty
  5. Fixing the code after an error makes the field valid again
03

Hints

0/3
Track lessons0 of 8 done

In this track you'll write your own validation rules, tie one field to another, and write error messages a screen reader can announce.

Intermediate level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 8 done

In this track you'll write your own validation rules, tie one field to another, and write error messages a screen reader can announce.

Intermediate level, 8 lessons, 1.5 hours in total.