Menu
CoddyTech

Validation Guards

Part of the Fundamentals section of Coddy's Angular journey. Lesson 34 of 55.

A submission handler should check its inputs before changing saved state. This rating form accepts whole-number ratings from one to five; a value outside the range sets an error and returns before committing.

rating=7; savedRating=2; error="";
submit(){if(this.rating<1 || this.rating>5){this.error="Out of range";return;}this.savedRating=this.rating;this.error="";}

An early return keeps the previous saved value intact. Keep feedback separate from stored data and clear the feedback after a valid submission. A disabled button alone is not a substitute for a guard inside the handler.

challenge icon

Challenge

Medium

Validate a saved label before committing it. Trim the draft. Reject an empty trimmed name with Name required. Keep the previous saved value on rejection, initially None, and clear error on a valid save. Use IDs draft, save, saved and error.

Edit the supplied files. Press Run preview to refresh the preview after edits, then use Check or Run code to grade your work. Keep the requested element IDs.

Try it yourself

<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="styles.css"></head><body><app-root></app-root><script type="module" src="main.ts"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals