How do you write a custom validator?

Angular forms · Freshers and experienced

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