NashTech Insights

Custom Validators in Angular Reactive Forms

Aanchal
Aanchal
Table of Contents
Custom validators in angular reactive forms

Introduction

Angular Reactive Forms are a powerful tool for building dynamic and interactive web forms. They allow you to create complex forms with validation and data-binding capabilities. While Angular provides built-in validators for common use cases, there are times when you need to implement custom validators to meet specific requirements. In this blog, we will explore how to create and use custom validators in Angular Reactive Forms.

Why Custom Validators?

Custom validators come in handy when you have unique validation rules that cannot be achieved using Angular’s built-in validators like required, minLength, maxLength, or pattern. These custom rules might involve complex logic or depend on multiple-form controls. By creating custom validators, you can extend Angular’s validation capabilities to accommodate your project’s specific needs.

Creating a Custom Validator

To create a custom validator in Angular, you’ll need to define a function that takes a FormControl as its argument. This function should return an object if the validation fails, where the keys represent validation error names, and the values provide additional information about the error.

Here’s a basic example of a custom validator that checks if a string contains at least one uppercase letter:

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

export function uppercaseValidator(control: AbstractControl): ValidationErrors | null {
  const value: string = control.value as string;
  if (value && !/[A-Z]/.test(value)) {
    return { noUppercase: true };
  }
  return null;
}

In this example, the uppercaseValidator function returns a validation error object with the key noUppercase if the input string does not contain any uppercase letters. Otherwise, it returns null, indicating a successful validation.

Using Custom Validators

Once you’ve created your custom validator function, you can use it in your Angular Reactive Forms by adding it to the Validators array when defining form controls. Here’s an example of how to use the uppercaseValidator in a form:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { uppercaseValidator } from './validators';

@Component({
  selector: 'app-custom-validator-demo',
  templateUrl: './custom-validator-demo.component.html',
})
export class CustomValidatorDemoComponent {
  myForm: FormGroup;

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

In this code, we import the uppercaseValidator function and use it as one of the validators for the ‘username’ form control. Now, when a user enters a username that doesn’t contain any uppercase letters, the ‘username’ control will have a validation error with the key noUppercase.

Displaying Custom Validation Errors

To provide meaningful feedback to users, you should display custom validation errors in your template. You can access these errors using Angular’s getError method on a form control. Here’s an example of how to display the noUppercase error in an Angular template:

<div [formGroup]="myForm">
  <label for="username">Username</label>
  <input type="text" id="username" formControlName="username">
  <div *ngIf="myForm.get('username').hasError('noUppercase')">
    Username must contain at least one uppercase letter.
  </div>
</div>

In this example, we use the myForm.get('username').hasError('noUppercase') condition to check if the ‘username’ control has the noUppercase error, and if so, we display a corresponding error message.

Conclusion

Custom validators in Angular Reactive Forms allow you to implement complex validation rules tailored to your project’s requirements. By creating custom validation functions and integrating them into your forms, you can ensure that your application collects and validates data effectively. Custom validators are a valuable tool for building robust and user-friendly web forms in Angular.

Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency

Aanchal

Aanchal

Aanchal Agarwal is a Software Consultant at NashTech. Her practice area is web development. She is recognized as a multi-talented, multitasker, and adaptive to the different work environments. Her hobbies include watching movies, listening to music, and traveling. She likes to read books and explore new things.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: