Skip to content
Exercise · Errors · lesson 10 of 10

Exercise: a validation error

Write an error class ValidationError and a function function validateUser(user) that checks data from a form. The call new ValidationError(message, field) creates an instance of Error whose message is the given text, field is the name of the wrong form field, and name is "ValidationError". The function validateUser gets an object with the properties name and age. If the name is empty, it throws a ValidationError with field equal to "name". If the age is less than 0 or greater than 150, it throws a ValidationError with field equal to "age". Otherwise the function returns true.

  • validateUser({ name: "Ann", age: 0 }) → true
  • validateUser({ name: "", age: 30 }) → throws a ValidationError with field equal to "name"
  • new ValidationError("too old", "age").name → "ValidationError"

Constraints: name is always a string, age is always a whole number, the limits 0 and 150 are allowed, and each test has at most one wrong property.

Do not add extra imports unless the task says so explicitly.

validate-user.js — javascript
javascript · 7 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way