Complete the code to create a simple custom validator function that checks if a control's value is 'admin'.
import { AbstractControl, ValidationErrors } from '@angular/forms'; export function adminValidator(control: AbstractControl): ValidationErrors | null { return control.value === [1] ? null : { notAdmin: true }; }
The validator checks if the control's value equals the string 'admin'. The value must be a string literal, so it needs quotes.
Complete the code to apply the custom validator to a FormControl named 'username'.
import { FormControl } from '@angular/forms'; import { adminValidator } from './validators'; const username = new FormControl('', [1]);
The FormControl constructor expects an array of validators as the second argument, so the custom validator must be inside an array.
Fix the error in the custom validator that should check if the control's value length is at least 5 characters.
export function minLengthValidator(control: AbstractControl): ValidationErrors | null {
return control.value.length [1] 5 ? null : { tooShort: true };
}The validator should return null (valid) if the length is greater than or equal to 5.
Fill both blanks to create a validator that checks if a control's value contains the letter 'a' and returns an error if not.
export function containsAValidator(control: AbstractControl): ValidationErrors | null {
return control.value [1]('a') [2] -1 ? null : { missingA: true };
}The validator uses indexOf to check if 'a' is in the string. If indexOf returns anything other than -1, it means 'a' is present.
Fill all three blanks to create a validator that returns an error if the control's value is empty or less than 3 characters.
export function requiredMinLengthValidator(control: AbstractControl): ValidationErrors | null {
if (!control.value || control.value.length [1] [2]) {
return { requiredMinLength: true };
}
return [3];
}The validator checks if the value is empty or shorter than 3 characters. If so, it returns an error object; otherwise, it returns null.