Bird
0
0

Identify the error in this custom validator code snippet:

medium📝 Debug Q14 of 15
Angular - Reactive Forms
Identify the error in this custom validator code snippet:
function minLengthFive(control: AbstractControl) {
  if (control.value.length < 5) {
    return { minLengthFive: true };
  }
}
AIncorrect error object key name
BMissing return null for valid input
CUsing control.value.length without checking null
DValidator should return boolean instead of object
Step-by-Step Solution
Solution:
  1. Step 1: Check for runtime errors

    The code accesses control.value.length without checking if control.value is null or undefined, causing TypeError when value is null (common for new FormControls).
  2. Step 2: Angular validator best practice

    Always check if (control.value == null) return null; before accessing properties like length. Explicit return null; for valid cases is also recommended.
  3. Final Answer:

    Using control.value.length without checking null -> Option C
  4. Quick Check:

    control.value can be null causing crash [OK]
Quick Trick: Always check control.value != null before .length [OK]
Common Mistakes:
MISTAKES
  • Not checking control.value for null before .length
  • Returning undefined instead of null for valid input
  • Confusing error object keys with validator names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes