Bird
0
0

Which of the following correctly defines a synchronous custom validator function in Angular that checks if a control's value is a non-empty string?

easy📝 Syntax Q3 of 15
Angular - Reactive Forms
Which of the following correctly defines a synchronous custom validator function in Angular that checks if a control's value is a non-empty string?
Afunction nonEmptyValidator(control: AbstractControl): ValidationErrors | null { return control.value ? null : { empty: true }; }
Bfunction nonEmptyValidator(control: AbstractControl): boolean { return control.value !== ''; }
Cfunction nonEmptyValidator(control: AbstractControl): void { if (!control.value) { return { empty: true }; } }
Dfunction nonEmptyValidator(control: AbstractControl): string | null { return control.value ? null : 'empty'; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the validator signature

    A synchronous custom validator must return either null if valid or an object of type ValidationErrors if invalid.
  2. Step 2: Analyze each option

    function nonEmptyValidator(control: AbstractControl): ValidationErrors | null { return control.value ? null : { empty: true }; } returns null or an error object correctly.
    function nonEmptyValidator(control: AbstractControl): boolean { return control.value !== ''; } returns a boolean, which is invalid.
    function nonEmptyValidator(control: AbstractControl): void { if (!control.value) { return { empty: true }; } } returns void and does not return the error object properly.
    function nonEmptyValidator(control: AbstractControl): string | null { return control.value ? null : 'empty'; } returns a string or null, which is not the expected return type.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Validator returns null or error object [OK]
Quick Trick: Validator returns null or error object [OK]
Common Mistakes:
MISTAKES
  • Returning boolean instead of ValidationErrors or null
  • Not returning anything (void)
  • Returning string instead of object or null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes