What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief period while it checks for availability, allowing the submit button to become clickable.

My objective is to keep the submit button disabled during the email availability check.

validateEmailAvailability(): AsyncValidatorFn {
    return (control: AbstractControl): Observable<any> => {
        return control.valueChanges.pipe(
            debounceTime(500),
            distinctUntilChanged(),
            take(1),
            switchMap(_ => this
                .checkEmailExists(control.value)
                .pipe(map(isExists => (isExists ? ({ isExists: true}) : null)))
            ),
        )
    }
}

Answer №1

To enhance your code, consider utilizing the powerful combination of rxJs operators Tap and Finalize: https://rxjs-dev.firebaseapp.com/api/operators/tap
https://rxjs-dev.firebaseapp.com/api/operators/finalize

optimizeEmailValidation(): AsyncValidatorFn {
        return (control: AbstractControl):Observable<any> => {
            return control.valueChanges.pipe(
                debounceTime(500),
                tap(() => this.disableSubmit = true),
                distinctUntilChanged(),
                take(1),
                switchMap(_ => this.checkEmailExists(control.value)
                    .pipe(
                        map(isExists => (isExists ? ({ isExists: true}) : null)),
                        finalize(() => this.disableSumbit = false)
                    )),
            )
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transitioning create-react-app from JavaScript to Typescript

A few months ago, I began a React project using create-react-app and now I am interested in transitioning the project from JavaScript to TypeScript. I discovered that there is an option to create a React app with TypeScript by using the flag: --scripts-v ...

Adding a child node before an empty node in Chrome with JavaScript Rangy

When attempting to insert a node before an empty element at the start of another element, a problem was noticed. Here is the initial setup: <p>|<span />Some text</p> By using range.insertNode() on a Rangy range to add some text, Chrome ...

Tips for limiting a website to load exclusively within an iframe

I am managing two different websites: https://exampleiframe.com (a third-party website), https://example.com (my own website) My goal is to limit the loading of https://example.com so that it only opens within an iframe on https://exampleiframe.com To a ...

What could be the reason for the data being retrieved but not showing up on the web page?

When fetching data from an API, I encounter a problem where the Loader displays but the data never shows up on the page. The inconsistency of this behavior is puzzling to me. This issue seems to be more prevalent on smartphones than on computers. useEffec ...

Confirmation checkbox that retains original value if canceled

Imagine a scenario where there is a checkbox value. When the checkbox value changes, the user is asked, "Do you want to SHOW this item on the website?" or "Do you want to HIDE this item on the website?" Everything seems to be working fine, except for one ...

I've noticed that the list item vanishes unexpectedly when utilizing Primeng drag-and-drop feature

Whenever I try to drag an item from one list to another in the Primeng picklist, the item disappears until it is dropped. <p-dialog [(visible)]="showMarker" (onHide)="hideDialogChild()" [contentStyle]="{'overflow':'visible'}" h ...

If a DOM element contains any text node, completely remove the element

Currently, I am using WordPress and my theme automatically generates a menu where all the items are marked with "-". It can be quite annoying. I have tried to fix it by replacing all the option values instead of just removing the "-", but I couldn't g ...

Use Javascript to display or conceal events on a fullcalendar interface

I am in the process of creating a religious calendar as part of a project that displays various events from major religions. Using the full calendar, I have included a "religion key" at the top of the calendar to differentiate between different faiths. My ...

Using Angular to inject various service implementations into a nested module

In my app, I have a class that implements ErrorHandler and is provided at the root level. There are 3 modules in my app, two of which can use the ErrorHandler at the root level, but one of them requires a different version of the ErrorHandler. I attempted ...

Chrome is experiencing a delay in closing the Select Option dropdown menu

On my webpage, I have two select option buttons placed on different tabs. Whenever one button is changed, I want to update the value of the other button and assign it to a specific element like a span in the example code provided. While everything works sm ...

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

Encountered an issue while attempting to access a property from an undefined source

I am struggling with this code as I am unable to correctly split the JSON data. The error message I keep encountering is: TypeError: Cannot read property "cu_id" from undefined. Here is a snippet of the JSON data (since it's too large to di ...

Is it time to execute a mocha test?

Good day, I am currently exploring the world of software testing and recently installed Mocha. However, I seem to be encountering an issue with running a basic test that involves comparing two numbers. Can someone please guide me on why this is happening a ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

How can I use jQuery to target and modify multiple elements simultaneously

I've been struggling for the past couple of hours trying to use prop to change the values of two items in a button. One item updates successfully, but the other one doesn't and I can't figure out why. Here is the HTML: <input type=&apos ...

Issue: The error message "articales.forEach is not a function" is indicating

app.get('/', (req, res) => { const articales = { title: 'Test Articles', createdAt: Date.now(), description: "Test Description" } res.render('index', { articales : articales }) }) <div ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

Is it possible to update parent data using a child component?

What is the correct way to update parent data using a child component? In the child component, I am directly modifying parent data through props. I'm unsure if this is the right approach. According to the Vue documentation: When the parent proper ...

Ionic - Deleting an item from local storage

Currently, I am implementing local storage for my Ionic application. While I can successfully add and retrieve data from local storage, I encounter an issue when trying to delete a specific object - it ends up removing everything in the database. Moreover, ...

Having trouble with string matching in JavaScript?

My attempts to verify my Ajax response with a string have consistently resulted in a fail case being printed. Below is the section of code relating to my ajax request: var username = document.getElementById("name").value; var password = document.getEle ...