NashTech Blog

Custom Validators in Angular Reactive Forms

Table of Contents
Custom validators in angular reactive forms

Introduction

Angular Reactive Forms are a effective device for building dynamic and interactive web forms. They can help you create complicated bureaucracy with validation and statistics-binding abilties. While Angular affords integrated validators for not unusual use cases, there are instances while you need to put in force custom validators to satisfy unique necessities. In this blog, we can explore how to create and use custom validators in Angular Reactive Forms.

Why Custom Validators?

Custom validators come in available when you have unique validation guidelines that can not be carried out the use of Angular’s integrated validators like required, minLength, maxLength, or sample. These custom guidelines may involve complex logic or rely upon multiple-form controls. By growing custom validators, you may extend Angular’s validation abilities to house your assignment’s specific wishes.

Creating a Custom Validator

To create a custom validator in Angular, you’ll need to define a feature that takes a FormControl as its argument. This feature have to return an object if the validation fails, in which the keys represent validation blunders names, and the values provide additional statistics approximately the mistake.

Here’s a fundamental example of a custom validator that assessments if a string contains as a minimum 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 assist you to put into effect complicated validation guidelines tailor-made for your project’s necessities. By developing custom validation features and integrating them into your paperwork, you may ensure that your utility collects and validates information efficaciously. Custom validators are a treasured device for building strong and person-pleasant internet forms in Angular.

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

Picture of Aanchal

Aanchal

Aanchal Agarwal is a Sr. 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

Scroll to Top