Lesson 1 of 8
Custom validation
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
Add a validation rule the browser doesn't know
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.
Your task
Make #code valid only when it starts with SA followed by three digits.
Checks
5 checks- A correct code makes the field valid
- A code that doesn't start with SA is rejected
- A code with the wrong number of digits is rejected
- The rejection message isn't empty
- Fixing the code after an error makes the field valid again