WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Angular · Intermediate · question 34 of 100

How do you create and use custom validators in Angular forms?

📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

Creating and using custom validators in Angular forms involves a few steps. Let’s assume that you’ve already set up an Angular project and have a basic understanding of Angular forms.

1. **Create a custom validator function**

A custom validator is a simple function that takes input FormControl, FormGroup, or FormArray as an argument and returns an object containing validation errors or null if it’s valid.

Here’s a simple example to create a validator that checks if the input contains "angular":

import { AbstractControl, ValidationErrors } from '@angular/forms';

export function containsAngularValidator(control: AbstractControl): ValidationErrors | null {
  if ((control.value as string).toLowerCase().includes('angular')) {
    return { containsAngular: true }; // Return a validation error object if it contains the word "angular"
  }
  return null; // Return null if no error
}

2. **Add custom validator to a FormControl**

To add the custom validator to a FormControl, you’ll have to include it within the form control configuration. Let’s assume we are creating a form for user registration:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { containsAngularValidator } from './contains-angular.validator';

@Component({...})
export class AppComponent {
  registrationForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.registrationForm = this.fb.group({
      username: ['', [Validators.required, containsAngularValidator]],
      password: ['', Validators.required]
    });
  }
}

In this example, we have added the ‘containsAngularValidator‘ and the ‘Validators.required‘ as the validators for the ’username’ field.

3. **Display validation errors in the template**

In the component template, you can display custom validator errors using the same technique you use for built-in validators. Here’s an example:

<form [formGroup]="registrationForm">
  <div>
    <label for="username">Username:</label>
    <input type="text" id="username" formControlName="username" />
    <div *ngIf="registrationForm.controls.username.errors?.containsAngular">
      The username cannot contain the word "angular".
    </div>
  </div>
  <!-- password and other form fields -->
  <button type="submit" [disabled]="!registrationForm.valid">Register</button>
</form>

Now, when you enter a username containing the word "angular," it will display a validation error.

These are the key steps to create and use custom validators in Angular forms. You can apply similar methods for creating more complex validators or using them with reactive or template-driven forms.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Angular interview — then scores it.
📞 Practice Angular — free 15 min
📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

All 100 Angular questions · All topics