Skip to main content

Custom Validators in Angular



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 the ReactiveFormsModule 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 FormBuilder, FormGroup 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 namedname, age 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 theadd-employee.component.ts component by modifying its code as 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-employee to the app.component.ts to make use of it.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...