Challenge - 5 Problems
Custom Validator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate1:30remaining
What happens when a custom validator returns null?
In Angular, a custom validator function returns
null. What does this mean for the form control's validity?Angular
function myValidator(control: AbstractControl): ValidationErrors | null { return null; }
Attempts:
2 left
💡 Hint
Think about what Angular expects from a validator when there are no problems.
✗ Incorrect
In Angular, a validator returns null to indicate the control is valid. Any object returned means errors.
📝 Syntax
intermediate2:00remaining
Identify the correct custom validator syntax
Which of the following is the correct way to write a synchronous custom validator function in Angular?
Attempts:
2 left
💡 Hint
Check the return type and syntax carefully.
✗ Incorrect
A custom validator must return null if valid or an object with error info if invalid. Option C follows this pattern correctly.
❓ state_output
advanced2:00remaining
What is the validation state after applying this custom validator?
Given this custom validator and a form control with value 'abc', what is the control's
errors property after validation?Angular
function startsWithAValidator(control: AbstractControl): ValidationErrors | null { return control.value.startsWith('A') ? null : { startsWithA: true }; } const control = new FormControl('abc', startsWithAValidator); const errors = control.errors;
Attempts:
2 left
💡 Hint
Check if the string 'abc' starts with 'A'.
✗ Incorrect
The value 'abc' does not start with 'A', so the validator returns the error object { startsWithA: true }. This sets the control's errors property.
🔧 Debug
advanced2:30remaining
Why does this custom validator cause a runtime error?
This custom validator throws an error when the form control value is empty. Why?
Angular
function positiveNumberValidator(control: AbstractControl): ValidationErrors | null { if (control.value == null || control.value <= 0) { return { notPositive: true }; } return null; }
Attempts:
2 left
💡 Hint
Think about what happens if control.value is empty or missing.
✗ Incorrect
If control.value is null or undefined, the comparison control.value <= 0 throws a runtime error because you cannot compare null/undefined with a number.
🧠 Conceptual
expert3:00remaining
How to create a reusable parameterized custom validator?
You want to create a custom validator that checks if a control's value length is at least a minimum number, passed as a parameter. Which approach correctly creates this reusable validator?
Attempts:
2 left
💡 Hint
Remember Angular expects a function returning a validator function for parameterized validators.
✗ Incorrect
Option A correctly returns a function that takes a control and returns errors or null. This pattern allows passing parameters to the validator.