How do you write a custom validator?
Model answer
A validator is a function that receives a control and returns null when the value is valid, or an object describing the error when it is not: (control) => control.value.includes(' ') ? { noSpaces: true } : null. Add it to the control's validator list and show a message when control.hasError('noSpaces').
For rules involving two fields, such as password and confirm password, put the validator on the FormGroup so it can compare them.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- What is the difference between template-driven and reactive forms?
- How do you add validation to a reactive form?
- What are async validators and when do you need one?
- What are FormArray and dynamic forms?
- What is the difference between valueChanges and statusChanges, and how do you use them safely?
- What do touched, dirty and pristine mean?