Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change.

I have the ability to add multiple controls to my form, and here is how I have structured it:

    ngOninit(){
      this.userForm = this._formBuilder.group({
       others: this._formBuilder.array([])  //multiple
      });

      this.onAddControl();  //allows adding multiple items
    }

    onAddControl(){

        return this._formBuilder.group({
         email: ['' [this._validateServ.emailDoesntExistsValidator.bind(this._validateServ)]
         ],

       });
   }
 }

Now, let's take a look at the _validateServ:

emailDoesntExistsValidator(control) {
  if (control.value != undefined) {
    if(!this.emailValueValidator(control)){
       return this._authService.checkExists("email",control.value)  //http request
        .map(response => {
          if (response) {
            return {'emailTaken': true};
         }
      });
    }

  }
}

I want the email validation to trigger on blur, as it involves an HTTP request and I would like to display a waiting message while the request is being processed. The current setup validates on each keypress, which is not ideal for me.

Answer №1

I'm not sure if delaying control validation is possible.

However, there are a couple of things you could postpone:

  • The HTTP request. By using the debounceTime() operator, you can wait for a specified number of milliseconds after the user has stopped typing before sending the request. Check out an example here.
  • The display of error messages. Even though the field's validity is assessed as the user types, you have the option to delay showing the error until the field loses focus. Set a flag to true when the input blurs:
    <input (blur)="displayError=true">
    . Then, utilize that flag to determine when to display the error:
    <div *ngIf="error && displayError">Error message</div>
    .

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

The Next.js website displays a favicon in Chrome, but it does not appear in Brave browser

As I work on my debut next.js website, I am configuring the favicon in index.js like this: <Head> <title>Create Next App</title> <link rel="icon" href="/favicon.ico" /> </Head> Initially, all my source ...

Accessibility issues detected in Bootstrap toggle buttons

I've been experimenting with implementing the Bootstrap toggle button, but I'm having an issue where I can't 'tab' to them using the keyboard due to something in their js script. Interestingly, when I remove the js script, I'm ...

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

How can one address the issue of undefined data within table cells?

I have encountered an issue while reading and displaying an XML file on a webpage using a JavaScript script. The problem arises when the page loads, and the information inside the cells of the table shows as "UNDEFINED". The intended display should include ...

Implement a jQuery DataTable using JSON data retrieved from a Python script

I am attempting to create an HTML table from JSON data that I have generated after retrieving information from a server. The data appears to be correctly formatted, but I am encountering an error with DataTable that says 'CIK' is an unknown para ...

The best location for storing Typescript files within an ASP.NET Core project

My Typescript app is built on AngularJS 2 with ASP.NET Core, and currently I store my TS files in the wwwroot directory. While this setup works well during development, I am concerned about how it will function in production. I aim to deploy only minified ...

I noticed that when I include the www in the URL, I am unable to retrieve the API results. However, when I exclude the

Whenever I try to access my website through www.mywebsite.in, it fails to display my data. However, if I visit the site without the www prefix, everything works fine and I can retrieve data from the database. I'm currently utilizing APIs for both get ...

Ensure exclusive access to variables for sequential updates in jQuery or JavaScript

I am currently developing a series of small functions in jQuery aimed at tracking how long it takes for a user to complete a form. The form consists of various input types and 'continue' buttons located within the form itself. Below are some sa ...

Showing text instantly upon clicking a radio button, in real-time

I'm working with a set of radio buttons that are linked to numbers ranging from 1 to 24. I need to show the selected number in another part of the page when a radio button is clicked. What would be the best way to achieve this? ...

What is the process for tallying checked checkboxes in a functional component using React Native?

The Whole Code is Right Here Within this code, you will find two flat lists: one displaying category names and the other showing their subcategories with checkboxes. I am looking to implement a feature where if a user checks multiple or just one checkbox ...

Encountering the error message "Attempting to access properties of undefined (specifically 'map')". Despite having the array properly declared and imported

I am facing an issue while trying to iterate through an array and display names for each person. Despite declaring the array properly, it is returning as undefined which is causing the .map function to fail. Can you help me figure out where I am making a m ...

Blend Mode / Vue CLI / Remote server routing

I'm looking for a solution to set up a proxy in an AngularCLI/Webpack environment. The main goal is to forward requests from http://localhost:4200/rest to https://someserver.com/somepath/rest. One challenge is that the endpoint is using HTTPS instead ...

The socket context provider seems to be malfunctioning within the component

One day, I decided to create a new context file called socket.tsx: import React, { createContext } from "react"; import { io, Socket } from "socket.io-client"; const socket = io("http://localhost:3000", { reconnectionDela ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Working with numerous query parameters within AngularJS

When interfacing with an external service, I’m receiving query parameters in the following format: url/?error=someError&error_description=someErrorDescription In my app.js file, I have attempted to handle this using the routeProvider as shown below ...

Avoid changing the regex pattern if it is surrounded by a specific character

I want to change all occurrences of strings enclosed by - with strings enclosed by ~, unless the string is again surrounded by *. For instance, consider this string... The -quick- *brown -f-ox* jumps. ...should be altered to... The ~quick~ *brown -f-ox ...

Image-switching button

I'm new to JavaScript and struggling with my first code. I've been staring at it for two days now, but can't figure out what's wrong. The goal is to create an HTML page where the user can change an image by clicking on a button, and th ...

Tips for integrating Laravel's blade syntax with Vuejs

Can you guide me on integrating the following Laravel syntax into a Vue.js component? @if(!Auth::guest()) @if(Auth::user()->id === $post->user->id) <a href=#>edit</a> @endif @endif ...

Error: The property 'create' of undefined cannot be read (Material UI/enzyme)

When I mount a component, I encounter an error that does not occur when using shallow rendering. The specific error is: TypeError: Cannot read property 'create' of undefined at stylesOrCreator (node_modules/@material-ui/core/CircularProgress/C ...