Bird
0
0

Identify the issue in this custom validator code snippet:

medium📝 Debug Q6 of 15
Angular - Reactive Forms
Identify the issue in this custom validator code snippet:
function maxLengthValidator(control: AbstractControl): ValidationErrors | null {
  if (control.value.length > 10) {
    return { maxLength: true };
  }
}
AThe validator should throw an error instead of returning an object
BThe error object key should be 'maxLengthExceeded' instead of 'maxLength'
CThe function should return a boolean instead of an object
DThe function does not return null when the input is valid
Step-by-Step Solution
Solution:
  1. Step 1: Check return values

    A custom validator must return null if the input is valid.
  2. Step 2: Analyze the code

    If control.value.length > 10, it returns an error object.
    Otherwise, it returns nothing (undefined).
  3. Step 3: Identify the problem

    Not returning null explicitly when valid causes Angular to treat the validator as invalid or inconsistent.
  4. Final Answer:

    The function does not return null when the input is valid -> Option D
  5. Quick Check:

    Always return null if valid [OK]
Quick Trick: Always return null if valid [OK]
Common Mistakes:
MISTAKES
  • Omitting return null for valid inputs
  • Returning boolean instead of ValidationErrors or null
  • Using incorrect error object keys

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes