0
0
Angularframework~10 mins

Custom validators in Angular - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a simple custom validator function that checks if a control's value is 'admin'.

Angular
import { AbstractControl, ValidationErrors } from '@angular/forms';

export function adminValidator(control: AbstractControl): ValidationErrors | null {
  return control.value === [1] ? null : { notAdmin: true };
}
Drag options to blanks, or click blank then click option'
A'admin'
Badmin
C'user'
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around 'admin' causing a reference error.
Returning true or false instead of null or an error object.
2fill in blank
medium

Complete the code to apply the custom validator to a FormControl named 'username'.

Angular
import { FormControl } from '@angular/forms';
import { adminValidator } from './validators';

const username = new FormControl('', [1]);
Drag options to blanks, or click blank then click option'
A['adminValidator']
B[adminValidator]
CadminValidator
D{ adminValidator }
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the validator function directly without wrapping in an array.
Passing the validator name as a string instead of the function.
3fill in blank
hard

Fix the error in the custom validator that should check if the control's value length is at least 5 characters.

Angular
export function minLengthValidator(control: AbstractControl): ValidationErrors | null {
  return control.value.length [1] 5 ? null : { tooShort: true };
}
Drag options to blanks, or click blank then click option'
A>=
B!==
C===
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' which would mark valid values as invalid.
Using '===' which only checks exact length 5.
4fill in blank
hard

Fill both blanks to create a validator that checks if a control's value contains the letter 'a' and returns an error if not.

Angular
export function containsAValidator(control: AbstractControl): ValidationErrors | null {
  return control.value [1]('a') [2] -1 ? null : { missingA: true };
}
Drag options to blanks, or click blank then click option'
Aincludes
BindexOf
C!==
D===
Attempts:
3 left
💡 Hint
Common Mistakes
Using includes but comparing with -1 which is incorrect.
Using '===' instead of '!==' causing wrong validation.
5fill in blank
hard

Fill all three blanks to create a validator that returns an error if the control's value is empty or less than 3 characters.

Angular
export function requiredMinLengthValidator(control: AbstractControl): ValidationErrors | null {
  if (!control.value || control.value.length [1] [2]) {
    return { requiredMinLength: true };
  }
  return [3];
}
Drag options to blanks, or click blank then click option'
A<
B3
Cnull
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true or false instead of null for valid values.
Using wrong comparison operators.