Skip to main content

Custom Validators in Angular


In this article, we shall focus on, how to create a custom validator and assign it to a FormControl. Angular provides us with few in-built validators which can be used for validation. But there may be some scenarios in which we need to give custom validation to our control. In such a case, we create a custom validator.

Let's start with an example program. First, create an angular application using

ng new angular-app

Then enter into the project using

cd angular-app

To use reactive forms, we need to import ReactiveFormsModule in ourapp.module.ts file. Let's modify the code in our app.module.ts to import theReactiveFormsModule and add it to imports array to make use of it.

Now, let's create a new component named, AddEmployeeComponent.

ng g c add-employee

Let's modify the app-employee.component.ts file

We are about to create a simple form to get employee details such as their name, age and gender. To make use of reactive forms we have to import FormBuilderFormGroup and Validators. Next, we need to inject theFormBuilder to the constructor with a name 'fb'.

In ngOnInit() life cycle event, we create a FormGroup namedemployeeForm and assign a formGroup by creating formGroup with FormBuilder object 'fb'. The FormGroup contains 3 formControl namednameage and gender. The name and gender FormControls are assigned a default value of empty string and apply single 'required' validation. Similarly, for age FormControl, we assign a default value of empty string and to this control we are going to apply multiple validation to this control, so we use array notation for it. So the code looks something like below

Let's create a custom validator and assign it to the age FormControl validation array. Create a folder named custom-validator and create a file named age-validator.ts and modify the code as below.

This custom validator is used to set validation when the given age is greater than 80. The FormControl value is obtained from the parameter ofageValidator() function. From the parameter, we get the value and check whether the age is greater than 80. If so, we set a validation with the name'ageInValid' to true and return it. If not, we return null to ensure that it passes the validation check. Now we are going to add the validation to the add-employee.component.ts component by modifying its code as below.


 below.

In add-employee.component.html file, we modify the code as below

In the forms tag, we apply the FormGroup name which is 'employeeForm'using the syntax [formGroup]='employeeForm' and to connect FormControl to html input element using formControlName property for the name, age and gender. To get the control, we use get() method along with the name of the FormControl name as parameter from which we can using validproperty we can check whether the control is valid or not and using touchedproperty we can check whether the control has been touched or not. To get the errors set to the control we use errors property from which we can get an object with error parameters set to true. To show up validation, we check whether the control is valid or not and also check touched property to show up validation. To show up custom validation we use the syntax in ngFordirective.

!employeeForm.get('age').valid && employeeForm.get('age').touched && employeeForm.get('age').errors.ageInValid

If the age entered is greater than 80, then the custom validator will set ageInValid to true. Now you can apply the selector string app-add-employeeto the app.component.ts to make use of it.


Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...