Angular: Show spinner loading and error messages with custom async validator in reactive forms (2023)

Angle enthusiast

·

follow

Published in

Geek culture
(Video) Angular Reactive Forms: ASYNC Validator And Loading Spinner (In An Input Element)

·

8 minutes of reading

·

24 listeopada 2022 r

--

Almost all of us have a Google account. You must have encountered the error message below while creating your account. This is an exampleasynchronous validationwhere we validateUsername fieldthroughasynchronous HTTP callto the server before submitting the form.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (3)

Inspired by this example, I created a small angular design that shows the points below:

(Video) Custom async validator | Reactive Forms | Angular 13+

  1. Asynchronous validatorsexecute only after passing the synchronous validators.
  2. Display with charging discwhile the Asynchronous Validator is running.
  3. Show error messages for both synchronous and asynchronous validators.

The application is as simple as the screenshot below. All we have is a text field to be filledUsername fieldI"Cabinet"button, which doesn't actually do anything in this example. The purpose of adding the button is to show how it is disabled/enabled during sync/async validation.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (4)

Application component template:

  1. The template contains the rootAsynchronous form group of formswhich has 1FormControl username.

2. We have that too"Cabinet"button, which is disabled whenasynchronous formmaVOIDstatus or whenFormControl usernameAre youTOCountry. FormControl is inTOindicate when asynchronous validation is in progress.

3. We show sync/async error messages (if any) in the template.

4. Finally, we also show onespinning readingnext to a text field when asynchronous validation is in progress.

Move toAppComponent class:

Starting withwith the OnInit lifecycle.

  1. Below is oneasynchronous formStructure.
this.asyncForm = this.fb.group({
User name: ['',
[Validators.required, GenericValidator.syncUsernameValidator(3, 10)],
this.usernameValidator.validate.bind(this.usernameValidator),
],
});

User namethere is a FormControl that has2 synchronous validators:Validators.requiredis built-in andsyncUserNameValidatoris the custom one we defined.

It has that too1 asyncvalidator:username validator.

2. Let's move on to the implementation of the Sync and Async Validator.

Below pWalidator Incwhich just checks that the minimum and maximum character length is as expected. This can be achieved using the built-inWalidatory.minlengthIValidators.max length. But I wanted to include a built-in custom sync and custom async validator to demonstrate how the 3 behave together.

Data service:

Before we get to the custom async validator, let's check the file firstDataServiceclass below. In this service, we call the Fake JSON Placeholder API to check if the filethe username entered in the text box matches the username of one of the 10 users in their database.

If there is a match, ie. if the response from the API contains data, we returnobservable emitting truth.

If there is no match, ie. the username entered in the text field is unique and the API response is empty, we returnobservable emits false.

If there are errors during the API call, we simply return onenoticeable error.

Thecustom asynchronous validatorit's just a service class that implementsAsynchronous validatorinterface. This interface requires itimplement()must be implemented inside the class.

Theimplement()returnsObservable or promise validation error.

Based on the value returned byValidateUsername()wDataServiceor we will return oneValidation errorobject{duplicateUser:true}zero.

The object is returned if the username entered in the text box matches one of the 10 users in the database. If there is no match, null is returned.

If an error occurs during the API call, we return oneValidation errorobject{validationApiError:err.message}.

3. Now let's check all the scenarios.

Back to the goals we mentioned earlier.

=>Asynchronous validatorsexecute only after passing the synchronous validators.

As you can see in the Async Validator code highlighted below, we log the message as it executes. So the async validator will run only after passing the following sync validations.

(Video) 85. Create a Custom Asynchronous Validator in the Reactive Forms - Angular

  1. The Username field must be filled in.
  2. The username must be a minimum of 3 characters and a maximum of 10 characters.
Angular: Show spinner loading and error messages with custom async validator in reactive forms (5)

I'll go in first2 charactersin the Username field. Please note the error message displayed below the text field and the message logged to the console. Thatthe built-in validator passed, but the custom sync validator failed. We don't see a notification that the async validator is running.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (6)

Now let me remove the 2 characters I entered. We see 2 error messages below the text box suggesting thisvalidation of both native and custom sync failed. Again, no message is logged to the console to indicate execution of the Async Validator.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (7)

Now I've entered "Bret" in the Username field and the Async Validator starts working.The async validator was executed twice- once for the "Bre" string, then for the "Bret" string. Because the username "Bret" already exists in the fake JSON fallback database, we have displayed an error message.

Note that the Create button is also disabled.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (8)

But did the API call complete for both Async Validator executions?Let's check the Network tab.The API call to 'Bre' was aborted and only the API call to 'Bret' succeeded.. This may not happen all the time. It depends on how fast/slow the user types.

If the user types 'Bre' all at once, takes a while, and then types 't', then it is possible that the internal observable (HTTP request) for 'Bre' may finish executing before the next internal observable (HTTP request) for 'Bret' '" starts, in which case it is possible for both API calls to succeed.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (9)

=>Displaying the loading spinner while the Async Validator is executing.

When the async validator executes, theFormControl usernameAre youTOCountry. We use that to our advantage and present a spinner.

*ngIf="asyncForm.get("username").pending">
Angular: Show spinner loading and error messages with custom async validator in reactive forms (10)
Angular: Show spinner loading and error messages with custom async validator in reactive forms (11)

Let's analyze the scenariowhen the API fails or aborts. It fails for another reason. To check this scenario, I updated the endpoint in the DataService to non-existent.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (12)

We have shown the exact error message below the text box which you can see below. The Create button remains disabled.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (13)

=> Finally we come todisplays error messagesfor both sync and async validators.

(Video) How to add Async Validations to your Angular Reactive Forms

I really didn't want to populate the template with multiple ngIfs for each type of validation error. Instead, I moved this logic to a small method in the class to make the template look clean like below. One line of code is enough to display all error messages related to the fileFormControl username.

{{errorMap.username}}

We want the validation error messages to appear every timevalue/statezUser nameThe FormControl changes, but with a delay of 2 seconds.

Why are we looking for status changes? We don't really require it ifsynchronous validators onlyis defined in FormControl. But since we also have an async validator,we require checking for changes in the FormControl state to monitor the progress of the asynchronous validation execution.

connect Recent(
this.asyncForm.get('username').valueChanges,
this.asyncForm.get('username').statusChanges
)
.pipe (debounceTime(2000))
.subscribe((score) => {
console.log('[Control Value,Control Status]:', result);
this.setValidationMessage(this.asyncForm.get('username'), 'username');
});

We introducedvalue changeIstatusZmianyobservable toconnect Latestoperator. Each time the value/state changes,setValidationMessage()Called. We pass throughUser nameFormControl and control name as arguments.

Before we go tosetValidationMessage(),let's see below 2 properties in a class.

error map = {
User name: '',
};

ValidationMessages = {
User name: {
required: "Username is required",
minlength: "Username must be at least 3 characters long",
maxlength: "Username can be up to 10 characters long",
duplicate user: "Username already exists! Please choose another username"
},
};

error card propertyis the object it containsthe names of all FormControls (in the example: username is the only FormControl) as keys. The value for all keys will be an empty string.

Later, the value of the key will be set to the error message. we use iterror card propertyto display errors related to any FormControl in the template as below.

{{errorMap.username}}

validationMessages propertyis an object that contains the names of all FormControls as keys. The value corresponding to each key is a different object. The properties of this object are all "error names/types" possible for the FormControl key.

As seen below, the so-calledUser nameFormControl is a key whose value is the errorNames/Types object. For each error name/type, we have specified the error message to display. These error messages may look familiar.

ValidationMessages = {
User name: {
required: "Username is required",
minlength: "Username must be at least 3 characters long",
maxlength: "Username can be up to 10 characters long",
duplicate user: "Username already exists! Please choose another username"
},
};

Now let's move on tosetValidationMessage().

setValidationMessage(c: AbstractControl, controlName: string) {
this.errorMap[nazwakontroli] = „“;

if (c.error) {
this.errorMap[controlName] = Object.keys(c.errors).map((key: string) => {

if (key === "validationApiError") {
return c.error [key];
} Ellers {
return this.validationMessages[controlName][key];
}
})
.attach(';');
}
}

  1. Because there is only 1 FormControlUser nameit is obviousargument cis FormControl andcontrol nameis "username".

We reset the "username" property of the errorMap property object to "" to remove existing error messages.

this.errorMap[nazwakontroli] = „“;

2. IfUser nameThe FormControl has some errors, we extract the keys of the error property object on the FormControl to an array of keys usingitem keys. Each key is nothing but the name/type of the error, eg: required, minlength, maxlength, etc.

Then we use the so-calledcard operatoron the keyboard. If the key name is something other than "validationApiError", we directly extract the error message for that keyvalidation messages property.

We did not include "validationApiError" in the filevalidation messagesproperty because we cannot predict the error message when the API fails. It can be for any reason.

Therefore, in case of an error of type "validationApiError", we select the message from the error properties of the FormControl itself.

3. Finally we are hereto apply the join() function to the result of the map operatorto combine all error messages corresponding to the error types with a semicolon.

Check the screenshot below to see what the error messages look like for the 2 error types:required and minimum lengthare connected by semicolons.

Angular: Show spinner loading and error messages with custom async validator in reactive forms (14)

The complete working example can be found below.

FAQs

How do you optimize the performance of async Validators? ›

How do you optimize the performance of async validators?
  1. Template-driven forms: Set the property on ngModelOptions directive. <input [(ngModel)]="name" [ngModelOptions]="{updateOn: 'blur'}" />
  2. Reactive-forms: Set the property on FormControl instance. name = new FormControl('', { updateOn: 'blur' });

How to display validation messages using Angular? ›

Create a New Angular Project
  1. 1npm install -g @angular/cli. javascript.
  2. 1ng new ngValidation. javascript.
  3. 1cd my-app 2ng serve --open. javascript.
  4. 1// app.module.ts 2 3import { ReactiveFormsModule } from '@angular/forms'; 4 5imports: [ 6 BrowserModule, ReactiveFormsModule 7 ], javascript.
Sep 24, 2020

How do I check validators in reactive form? ›

In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.

How to do custom validation in reactive forms? ›

How to Make a Custom Form Validator with Angular Reactive Forms
  1. Create a FormGroup. The first step in creating a custom form validator is to create the form group that will contain all of the form controls. ...
  2. Create the Custom Validator Function. ...
  3. Add an Error Message to Your Form. ...
  4. Test Your Validator.
Mar 2, 2023

What is the difference between async validator and validator? ›

The creating an async validator is very similar to the Sync validators. The only difference is that the async Validators must return the result of the validation as an observable (or as Promise). Angular does not provide any built-in async validators as in the case of sync validators. But building one is very simple.

How to dynamically change the Validators in Angular? ›

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.

Why is async await better than callbacks? ›

Async functions not only allow the programmer to escape from callback hell and promise chaining in asynchronous code, but they also make the code seemingly synchronous.

What are the best practices for async API? ›

The best practice for organizing AsyncAPI files in your microservices architecture is to have a file per microservice. This way, you end up with multiple independent files that define your application. One publisher and one subscriber, both sharing the UserSignUp message.

How to show custom validator error message in validation summary? ›

As you can see in the above code, we have added a custom error message using the ModelState. AddModelError() method. The ValidationSummary() method will automatically display all the error messages added in the ModelState . Thus, you can use the ValidationSummary helper method to display error messages.

How to display error message in Angular material? ›

In angular material we have different selector present which can be used to show our error messages. mat-error: This is used to show the error, with the message attached to it. If the form is invalid then this message will be appear on screen with red color.

How to handle HTTP response error in Angular? ›

The basic way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError and catchError. The HTTP request is made, and it returns the data with a response if anything wrong happens then it returns an error object with an error status code.

Which keyword is used to display a custom error message? ›

The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.

Should I make space for error messages in forms? ›

Giving space for error messages, that might come in like 10% of the cases is not at all a good option. Actually, it is not Impossible or difficult to show the form validation messages as you have shown in option 2.

How do you Customise default form validation error messages? ›

How to customize built-in form validation error messages
  1. Grab the input element(s) with a querySelector / querySelectorAll .
  2. Add an event listener for the invalid event. When handling the event, under event. target. ...
  3. Add an event listener for the change event to reset the custom error when the input value changes.
Feb 1, 2020

How to get error from API response? ›

The REST API reports errors by returning an appropriate HTTP response code, for example 404 (Not Found), and a JSON response. Any HTTP response code that is not in the range 200 - 299 is considered an error.

How to show success or error message based on the response of the API in React js? ›

React Query Show Success Response Message with Bootstrap Example
  1. Step 1: Create React Project.
  2. Step 2: Install React Query and Axios Modules.
  3. Step 3: Setting Up Bootstrap.
  4. Step 4: Register React-Query in React.
  5. Step 5: Build Function Component.
  6. Step 6: Handle Success and Error Responses.
  7. Step 7: Update Global Component.
Apr 24, 2023

How do I set validation error? ›

How to create a custom validation error message that contains the name of the control that is being validated in InfoPath
  1. Design the Form.
  2. Add Data Validation by Using the User Interface.
  3. Add Data Validation by Using a Script.
  4. Test the Form.

What are the types of validators in reactive forms Angular? ›

The Angular ReactiveForms Module provides several Built-in validators out of the box. They are required , minlength , maxlength & pattern etc.

How to validate reactive form in Angular 12? ›

Angular 12 Reactive Forms Validation Example
  1. Step 1: Install Angular App. Here, in this step you need to create new ng app for this demo. ...
  2. Step 2: Import FormsModule. If you want to create form in angular app then you need to import FormsModule from @angular/forms library. ...
  3. Step 3: Form with ngModel. ...
  4. Step 4: updated Ts File.
Apr 4, 2023

How to reset validation in reactive form in Angular? ›

In the latest Angular versions you just need to run this. form. reset() (it marks everything as pristine and untouched and all that stuff under the hood) and then update value and validity for all the child form controls/groups/arrays.

How do I bypass validation rule using custom setting? ›

For each Validation Rule you want to bypass, you need to create a checkbox field (1). You can also create one checkbox field per object, if you want to bypass all Validation Rules (2). In the Custom Fields section select: New -> Checkbox -> Enter Field Label, Field Name -> Save.

How do you add a dynamic control in reactive form? ›

We are going to use the following steps in our existing code.
  1. Import Reactive Forms module in Dynamic Forms project.
  2. Import FormGroup and Form Control in app. component. ...
  3. Create FormGroup in app.component Class.
  4. Create a function in app. component. ...
  5. Explanation:
  6. Dynamic Forms template file changes in app. ...
  7. Explanation:
Feb 24, 2021

How to remove validation in existing control of a reactive form? ›

Either first use “clearValidators()” to remove all validators and then use “setValidators()” to set needed validation. Or directly use “setValidators()” with the needed validators only (without the validator you don't want to have). That's it for this article.

What is the difference between sync and async validators in angular? ›

Angular does not provide built-in type async Validation implmentation, it provides only for sync validation. The implementation of async validator is very similar to the sync validator. The only difference is that the async Validators must return the result of the validation as an observable or as Promise.

What is the difference between synchronous and asynchronous validators in angular? ›

Synchronous and asynchronous Validators are very similar - the main difference is that a sync Validator returns an error object instance directly, while the async version returns an Observable of the the same object. The most common use case for async Validators is doing a server validation via an HTTP Callback.

What is the difference between validate and validates custom validators? ›

validates is used for normal validations presence , length , and the like. validate is used for custom validation methods validate_name_starts_with_a , or whatever crazy method you come up with. These methods are clearly useful and help keep data clean.

Which method is used to add dynamic validation to the forms in Angular? ›

Dynamically Add Validators

We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.

How to show data dynamically in Angular? ›

Loading Components Dynamically in an Angular App
  1. Set up an Angular application with routing and lazy-loaded modules.
  2. Create an OIDC client in Okta.
  3. Add authentication to the Angular application.
  4. Capture authenticated user information and user claims.
  5. Simulate an external server call and implement the dynamic components.
Dec 8, 2021

How to use custom validators 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.

Why async is better than multithreading? ›

Asyncio vs threading: Async runs one block of code at a time while threading just one line of code at a time. With async, we have better control of when the execution is given to other block of code but we have to release the execution ourselves.

What is the difference between sync callback and async callback? ›

The main difference between synchronous and asynchronous callbacks is that synchronous callbacks are executed immediately, whereas the execution of asynchronous callbacks is deferred to a later point in time. This may be confusing at first, especially if you're coming from synchronous languages like PHP, Ruby or Java.

What is the difference between async await and callback and promise? ›

In summary, promises, callbacks, and async/await are all ways to handle asynchronous operations in JavaScript, with promises providing a more elegant way of handling async operations, callbacks being a more traditional way, and async/await providing a more convenient and readable way of handling async operations.

When should you not use async? ›

In addition, another situation when async may not be useful is when you have a single database server not utilizing connection pooling. If all requests hit the same database using a long running connection, it won't make a difference if the calls are asynchronous or synchronous.

What are the disadvantages of async API? ›

One disadvantage is that asynchronous requests can cause more load on web servers, because more requests are made per time interval than for synchronous applications. Another disadvantage is that there is more overhead and complexity for asynchronous applications in terms of code written.

Which is the best standard approach on error handling for async function? ›

When using async/await, it's a good idea to use the await keyword inside a try/catch block to properly handle errors. In this example, the fetch and response. json calls are wrapped in an await statement inside a try block. If an error occurs, it will be caught by the catch block and logged to the console.

What methods should you implement for your custom Validator? ›

A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.

How to display popup message in Angular? ›

These are the steps:
  1. Step 1: Creating an Angular 10 Project.
  2. Step 2: Adding Angular Material v10.
  3. Creating the Angular Modal Component.
  4. Adding a Material Card Container.
  5. Adding an HTML Form.
  6. Step 3: Using a Modal Dialog for Displaying Error Messages.
  7. Step 4: Opening the Popup Modal Dialog.
Aug 5, 2020

How to catch error status code in Angular? ›

To catch an HTTP status code in Angular, you can use the “pipe” operator and the “catchError” operator from the RxJS library. Here is an example of how to catch the HTTP status code in an Angular application: import { pipe, catchError } from 'rxjs/operators'; ...

How to handle HTTP 404 error in Angular? ›

So, let's get started!
  1. Create a new component for 404 page. First, you need to create a component to show the page, which will be displayed when error 404 occurs. ...
  2. Set a redirect to the 404 page. ...
  3. Connect Universal. ...
  4. Make the component sending 404 status.

How to handle 404 error from API in Angular? ›

If we get the 404 or the 500 error, we are going to redirect the user to a specific page. For other errors, we are going to show an error message in a modal form. The page that handles the 404 error is already created, so, let's continue on by creating a 500 (Internal server error) component.

How to write catch error in Angular? ›

Catch errors in the observable stream

Another option to catch errors is to use the CatchError Operator. The CatchError Operators catches the error in the observable stream as and when the error happens. This allows us to retry the failed observable or use a replacement observable.

How to find errors in Angular? ›

An error in an Angular application can either be a client-side error or server-side error:
  1. Client-side error: errors related to front-end code and the network — they throw 4xx status codes.
  2. Server-side error: errors related to back-end codes, database, and file system. They usually throw 5xx status codes.

How to display an error message in js? ›

Or, press F12. DevTools opens next to the webpage. In the top right of DevTools, the Open Console to view errors button displays an error about the webpage.

Which component should the developer add to the form to display error messages? ›

We will also use the Custom alert notification component to display the error messages.

What is the best way to handle errors in Angular? ›

The simplest way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError and catchError . Http request is made, and it returns the data with a response if anything wrong happens then it returns an error object with error status code.

How do you catch an error in observable? ›

The catchError operator takes as input an Observable that might error out, and starts emitting the values of the input Observable in its output Observable. If no error occurs, the output Observable produced by catchError works exactly the same way as the input Observable.

How do you catch exceptions and errors? ›

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

How to check lint errors in Angular? ›

ng lint run the linting tool on angular app code. It checks the code quality of angular project specified. It uses TSLint as default linting tool and uses the default configuration available in tslint. json file.

What is the command to check for TypeScript errors? ›

Test that the TypeScript is installed correctly by typing tsc -v into your terminal or command prompt. You should see the TypeScript version print out to the screen. For help on possible arguments you can type tsc -h or just tsc .

How does lazy loading work in Angular? ›

Lazy loading is a technology of angular that allows you to load JavaScript components when a specific route is activated. It improves application load time speed by splitting the application into many bundles. When the user navigates by the app, bundles are loaded as needed.

How to throw custom error message in JavaScript? ›

Custom Errors in JavaScript
  1. function throwAnError() { throw new Error('Something went wrong.'); } ...
  2. class BadRequestError extends Error { constructor(message) { super(message); ...
  3. class BadRequestError extends Error { constructor(message) { super(message); ...
  4. export class BadRequestError extends Error { constructor(error) {
May 22, 2020

How to show error message in popup window in JavaScript? ›

JavaScript Message Boxes: alert(), confirm(), prompt()
  1. alert(message): Display a popup box with the specified message with the OK button.
  2. confirm(message): Display a popup box with the specified message with OK and Cancel buttons.

Which method we can use in JavaScript for error message? ›

JavaScript try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Videos

1. Display Form Error Messages On Submit Using Angular Reactive Forms
(Code Shots With Profanis)
2. 💥 Angular Asynchronous Form Validators
(Angular University)
3. Angular Reactive Form | Async Validation | Form Validation | Complete Guide
(Teckie Share)
4. 108. Authentication - Add Loading Spinner and error message in the Signup Request Form - Angular.
(Leela Web Dev)
5. Angular Training Part 6 - Adding Custom Async Validations to a Reactive Form
(SiddAjmera)
6. Custom Async Form Validation With Backend - Angular 7
(Programming's Fun)

References

Top Articles
Latest Posts
Article information

Author: Carlyn Walter

Last Updated: 06/07/2023

Views: 5685

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Carlyn Walter

Birthday: 1996-01-03

Address: Suite 452 40815 Denyse Extensions, Sengermouth, OR 42374

Phone: +8501809515404

Job: Manufacturing Technician

Hobby: Table tennis, Archery, Vacation, Metal detecting, Yo-yoing, Crocheting, Creative writing

Introduction: My name is Carlyn Walter, I am a lively, glamorous, healthy, clean, powerful, calm, combative person who loves writing and wants to share my knowledge and understanding with you.