How to Create Custom Validators in Angular - DZone (2024)

In this blog post, we will learn how to create custom validators in Angular Reactive Forms. If you are new to reactive forms, learn how to create your first Angular reactive form here.

Let's say we have a login form as shown in the code below. Currently, the form controls do not have any validations attached to it.

ngOnInit() { this.loginForm = new FormGroup({ email: new FormControl(null), password: new FormControl(null), age: new FormControl(null) });}

Here, we are usingFormGroupto create a reactive form. On the component template, you can attachloginFormas shown in the code below. Using property binding, theformGroupproperty of the HTML form element is set tologinFormand theformControlNamevalue of these controls is set to the individualFormControlproperty of FormGroup.

This will give you a reactive form in your application:

How to Create Custom Validators in Angular - DZone (1)

Using Validators

Angular provides us many useful validators, including required, minLength, maxLength, and pattern. These validators are part of the Validators class, which comes with the @angular/forms package.

Let's assume you want to add a required validation to the email control and amaxLengthvalidation to the password control. Here's how you do that:

ngOnInit() { this.loginForm = new FormGroup({ email: new FormControl(null, [Validators.required]), password: new FormControl(null, [Validators.required, Validators.maxLength(8)]), age: new FormControl(null) });}

To work with validators, make sure to import them into the component class:

import { FormGroup, FormControl, Validators } from '@angular/forms'; 

On the template, you can use validators to show or hide an error message. Essentially, you are readingformControlusing theget()method and checking whether it has an error or not using thehasError()method. You are also checking whetherformControlis touched or not using the touched property.

If the user does not enter an email, then the reactive form will show an error as follows:

How to Create Custom Validators in Angular - DZone (2)

Custom Validators

Let us say you want the age range to be from 18 to 45. Angular does not provide us range validation; therefore, we will have to write a custom validator for this.

In Angular, creating a custom validator is as simple as creating another function. The only thing you need to keep in mind is that it takes one input parameter of typeAbstractControland it returns an object of akey-value pair if the validation fails.

Let's create a custom validator called ageRangeValidator, where the user should able to enter an age only if it's in a given range.

How to Create Custom Validators in Angular - DZone (3)

The type of the first parameter isAbstractControl, because it is a base class ofFormControl,FormArray, and FormGroup, and it allows you to read the value of the control passed to the custom validator function. The custom validator returns either of the following:

  1. If the validation fails, it returns an object, which contains a key-value pair. Key is the name of the error and the value is always Booleantrue.
  2. If the validation does not fail, it returns null.

Now, we can implement the ageRangeValidator custom validator in the below listing:

function ageRangeValidator(control: AbstractControl): { [key: string]: boolean } | null { if (control.value !== undefined && (isNaN(control.value) || control.value < 18 || control.value > 45)) { return { 'ageRange': true }; } return null;}

Here, we are hardcoding the maximum and minimum range in the validator. In the next section, we will see how to pass these parameters.

Now, you can use ageRangeValidator with the age control as shown in the code below. As you see, you need to add the name of the custom validator function in the array:

ngOnInit() { this.loginForm = new FormGroup({ email: new FormControl(null, [Validators.required]), password: new FormControl(null, [Validators.required, Validators.maxLength(8)]), age: new FormControl(null, [ageRangeValidator]) });}

On the template, the custom validator can be used like any other validator. We are using the ageRange validation to show or hide the error message.

If the user does not enter an age between 18 to 45, then the reactive form will show an error:

How to Create Custom Validators in Angular - DZone (4)

Nowthe age control is working with the custom validator. The only problem withageRangeValidatoris that the hardcoded age range only validates numbers between 18 and 45. To avoid a fixed range, we need to pass the maximum and minimum age toageRangeValidator.

Passing Parameters to a Custom Validator

An Angular custom validator does not directly take extra input parameters aside from the reference of the control. To pass extra parameters, you need to add a custom validator inside a factory function. The factory function will then return a custom validator.

You heard right: in JavaScript, a function can return another function.

Essentially, to pass parameters to a custom validator you need to follow these steps:

  1. Create a factory function and pass parameters that will be passed to the custom validator to this function.
  2. The return type of the factory function should be ValidatorFn which is part of @angular/forms
  3. Return the custom validator from the factory function.

The factory function syntax will be as follows:

How to Create Custom Validators in Angular - DZone (5)

Now you can refactor theageRangeValidatorto accept input parameters as shown in the listing below:

function ageRangeValidator(min: number, max: number): ValidatorFn { return (control: AbstractControl): { [key: string]: boolean } | null => { if (control.value !== undefined && (isNaN(control.value) || control.value < min || control.value > max)) { return { 'ageRange': true }; } return null; };}

We are using the input parameters max and min to validate age control. Now, you can useageRangeValidatorwith age control and pass the values for max and min as shown in the code below:

min = 10;max = 20;ngOnInit() { this.loginForm = new FormGroup({ email: new FormControl(null, [Validators.required]), password: new FormControl(null, [Validators.required, Validators.maxLength(8)]), age: new FormControl(null, [ageRangeValidator(this.min, this.max)]) });}

On the template, the custom validator can be used like any other validator. We are usingageRangevalidation to show or hide an error message:

In this case, if the user does not enter an age between 10 and 20, the error message will be shown as seen below:

How to Create Custom Validators in Angular - DZone (6)

And there you have it: how to create a custom validator for Angular Reactive Forms.

How to Create Custom Validators in Angular - DZone (2024)

FAQs

How to Create Custom Validators in Angular - DZone? ›

In Angular, creating a custom validator is as simple as creating another function. The only thing you need to keep in mind is that it takes one input parameter of type AbstractControl and it returns an object of a key-value pair if the validation fails.

How to add a custom validator in Angular? ›

To create a custom validator in Angular, you need to define a function that performs the validation logic and returns a validation error object if the validation fails. This function should adhere to the signature of ValidatorFn or AsyncValidatorFn based on whether your validation logic is synchronous or asynchronous.

How do you implement a custom validator? ›

Building a custom validator

Let's implement a validator function validateEmail which implements that interface. All we need to do is to define a function that takes a FormControl , checks if it's value matches the regex of an email address, and if not, returns an error object, or null in case the value is valid.

How to generate a validator in Angular? ›

How to Build a Generic Form Validator in Angular
  1. Step 1: Setup. ...
  2. Step 2: Import ReactiveFormsModule. ...
  3. Step 3: Create a generic validation class and password confirmation validator. ...
  4. Step 4: Add FormGroup and FormBuilder to each components and templates. ...
  5. Step 5: Use Generic Validation in each component.
Nov 3, 2020

How to use custom validator in template driven form in Angular? ›

in order to implement a custom validation directive, we need to implement the Validator interface, which only has the validate method. the validate method is going to call the validation creation function, and pass the control reference (the password control in this case) to the validator.

How to create custom tag in Angular? ›

Angular Elements
  1. Creating an element using Angular API.
  2. Communicating with a component using Input() and Output()
  3. Elements Build for use in other applications.
  4. Adding element to HTML page.
  5. Adding an element to a React application.
  6. Adding a component to a Vue application.
  7. Summary.
Jan 12, 2021

How to create a custom form validator to accept only valid JSON in Angular? ›

So, here is my modified version: import {AbstractControl, ValidationErrors, ValidatorFn} from '@angular/forms'; export function jsonValidator(control: AbstractControl): ValidationErrors | null { try { JSON. parse(control. value); } catch (e) { return { jsonInvalid: true }; } return null; };

What methods should you implement for your custom validator? ›

To implement a custom validation rule in Laravel, you'll need to create a new validation rule class. This class should extend the Illuminate\Validation\Rule class and define the passes and message methods. The passes method should return a Boolean value indicating whether the validation has passed or failed.

What is custom validator control with example? ›

You can use a CustomValidator control to ensure that the value specified is less than the amount in inventory and a RequiredFieldValidator control to ensure that the user enters a value into the TextBox control. If the input control is empty, no validation functions are called and validation succeeds.

What is a custom validation? ›

Custom validations enable you to add custom business logic to enforce data rules on your applications, dimensions, node types, and hierarchy sets. You work with custom validations on the Validations tab of the inspector for the data chain object that the validation was created for. Considerations.

How to set the validation in Angular? ›

Angular Form Validation Example Tutorial
  1. Step 1: Make one Angular Project. Install Angular globally by the following command. npm install -g @angular/cli. ...
  2. Step 2: Make one form inside app. component. html. ...
  3. Step 3: Explanation. There are two types of forms in Angular. Template Driven Forms.

What is validators required in Angular? ›

A validator is a function that processes a FormControl or collection of controls and returns a map of errors. A null map means that validation has passed.

How to set and remove validators in Angular? ›

In Angular, you can dynamically add or remove validations to a FormGroup by using the setValidators() method provided by the AbstractControl class. This method allows you to update the validators for a specific control within the form group.

How to create dynamic form validation in Angular? ›

Building dynamic formslink
  1. Prerequisites.
  2. Enable reactive forms for your project.
  3. Create a form object model.
  4. Define control classes.
  5. Compose form groups.
  6. Compose dynamic form contents.
  7. Supply data.
  8. Create a dynamic form template.

What is the return type of custom validator in Angular? ›

Creating Custom Validators

This function takes an AbstractControl object as an argument and returns an object of type ValidationErrors if the control is invalid, or null if the control is valid. The function checks whether the input string contains only numbers using a regular expression.

What is custom validation in Angular JS? ›

Custom Validation

AngularJS provides basic implementation for most common HTML5 input types: (text, number, url, email, date, radio, checkbox), as well as some directives for validation ( required , pattern , minlength , maxlength , min , max ).

How do I add a validator to FormGroup? ›

FormGroup: In Angular, you can dynamically add or remove validations to a FormGroup by using the setValidators() method provided by the AbstractControl class. This method allows you to update the validators for a specific control within the form group.

What is custom validation in angular JS? ›

Custom Validation

AngularJS provides basic implementation for most common HTML5 input types: (text, number, url, email, date, radio, checkbox), as well as some directives for validation ( required , pattern , minlength , maxlength , min , max ).

How to add a custom error message in Angular? ›

Let's walk through the steps to implement our custom validation message framework:
  1. Setting Up the Directive: Add the ValidationMessagesDirective to your Angular project.
  2. Creating the messages. ...
  3. Integrating with Form Controls: Apply the directive to form controls by binding the messages input.
Feb 11, 2024

Top Articles
What makes BNB a good investment for your business
Is Binance Coin Expected To Reach $1,000 Or More In The Next 5 Years? | Trading Education
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 6313

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.