Question presented to candidate: "Our sign-up form must reject usernames containing banned words, and must check with the server that the name is not already taken. How do you write custom validators for that in reactive forms?"
What a strong answer should cover:
- A validator is just a function,
ValidatorFn = (control: AbstractControl) => ValidationErrors | null:nullmeans valid, an object means invalid and its keys name the errors. - Configurable rules are written as a factory that takes options and returns the
ValidatorFn(forbiddenWords(["spam"])), the same shape asValidators.minLength(3). - Put useful detail in the error value (
{ forbiddenWord: { word: "spam" } }) so the template can build a message withhasError/getError. - Async validators (
AsyncValidatorFn) return a Promise or Observable; the control is PENDING meanwhile, and they only run once all sync validators pass. - Attach with
validators/asyncValidatorsin the options object, oraddValidatorslater; for template-driven forms wrap the function in a directive provided viaNG_VALIDATORS. - Know the four statuses:
VALID,INVALID,PENDING,DISABLED.
Clarifying questions expected:
- "Should the check run on every keystroke, or only on blur, given that one of them calls the server?"
- "Is the banned-word list static, or does it come from configuration?"
Code / implementation expected: Yes β a validator factory and an async validator on one control, with the resulting error objects shown.