Skip to content
tezvyn:

Create a custom synchronous validator for an Angular Reactive Form

Source: angular.devMediumHow cards are made

Create a custom synchronous validator for an Angular Reactive Form

Tests your grasp of the ValidatorFn contract and reactive form wiring. A strong answer: a function accepting AbstractControl returns null when valid or an error object when invalid, passed as the second FormControl argument. Red flag: returning booleans.

What's really being asked

This question probes whether you understand the ValidatorFn contract and the reactive forms paradigm where validation logic lives in the component class, not the template. Interviewers want to see that you know the exact return signature and how to wire a custom function into a FormControl instance.

The full answer

A strong response walks through four steps in order. First, define a plain function that takes an AbstractControl as its sole parameter and inspects control.value. Second, return null when the value is valid, which tells Angular to set the control status to VALID. Third, return a ValidationErrors object when the value is invalid, such as { forbiddenName: { value: control.value } }, which tells Angular to set the status to INVALID and populates the errors map. Fourth, apply the validator by passing it as the second argument to the FormControl constructor, like new FormControl('', myValidator), or by calling control.setValidators(myValidator) followed by control.updateValueAndValidity(). Mention that you read errors in the template with control.hasError('forbiddenName') or control.errors.

The mistakes people make

Red flags include returning true or false from the validator instead of null or an error object. Another mistake is describing HTML validation attributes like required or minlength on the template, which is the template-driven forms pattern, not reactive forms. Candidates also stumble by forgetting to invoke updateValueAndValidity after adding a validator dynamically, or by not typing the parameter as AbstractControl.

What usually comes next

Expect the interviewer to ask how to compose multiple validators, which you do by passing an array to the second argument. They may ask about the difference between sync and async validators, where async validators return a Promise or Observable and are passed as the third argument. Cross-field validation is another common follow-up, requiring a validator at the FormGroup level that compares sibling controls.

A concrete example

Suppose you want to block the name Bob. You write a function named forbiddenNameValidator that takes control: AbstractControl. Inside, if control.value is 'bob', you return { forbiddenName: true }. Otherwise you return null. In the component class, you create the control with name = new FormControl('', forbiddenNameValidator). In the template, you show an error with @if (name.hasError('forbiddenName')) { Name cannot be Bob. }.

Interview question

You need to attach a custom synchronous validator to an existing FormControl at runtime. Which approach is correct?

  • a.Call control.setValidators(validator), then call control.updateValueAndValidity()Correct
  • b.Pass the validator as the third argument to the FormControl constructor
  • c.Pass the validator as the second argument to the FormControl constructor
  • d.Call control.setValidators(validator) without any additional method calls
Why?

Calling setValidators followed by updateValueAndValidity forces Angular to re-evaluate an existing control dynamically. Using the constructor is only for new controls, omitting updateValueAndValidity leaves the status stale, and the third constructor argument is reserved for async validators.

Just read this? Test yourself on what you have been reading.

Read the original → angular.dev

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on angular — each one lists the topics its interview covers.

See open roles