Angular · Middle · Question 35 of 75

How do you write a custom synchronous validator?

export const noSpaces: ValidatorFn = (control) =>
  /\s/.test(control.value ?? "") ? { noSpaces: true } : null;

Explanation

Add it to the control's validators. The error key appears in control.errors, so the template can check control.hasError('noSpaces').

Further reading

Problem with a question

Angular · Middle · question 35

Test yourself

Take the Angular · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz