AngularJS supports asynchronous validation on blur

Using Angular JS version 1.5.6, I am looking to implement asynchronous input validation that occurs only on blur. However, I am unable to use modelOption: {debounce: 500} or modelOption: {updateOn: 'blur'} due to the directive being used with other directives.

I attempted the code below, but encountered a situation where no async validation is performed on the first blur, and subsequently, every typed character triggers the async validation, which is not the intended behavior.

function blurFocusDirective($http, $q) {
return {
  require: 'ngModel',
  link: function(scope, elm, attrs, modelCtrl) {
    elm.on('blur', function() {
      console.log('capture blur event');

      modelCtrl.$asyncValidators.myValidator = function(modelValue, viewValue) {
        return $http.get('/username-check/' + modelValue).then(
          function(response) {
            if (!response.data.validUsername) {
              return $q.reject(response.data.errorMessage);
            }
            return true;
          }
        );
      };
    });
  }
};

}

To observe the issue in action, you can check the following Plunker link. Press F12 to view the console log for more insights.

Note that the endpoint '/username-check/' is fictional and unrelated to the actual issue at hand. The problem lies in the fact that the async HTTP request fires on each typed character instead of just during blur.

Answer №1

If your code is experiencing an issue, it may be related to the onblur event triggering a new async validator every time there is a change in the ngModel. To address this, you can manually set the validation as shown below:

elm.on('blur', function() {
      console.log('capture blur event');

      $http.get('/username-check/' + modelCtrl.$modelValue).then(
        function(response) {
          if (response.data.validUsername)
            modelCtrl.$setValidity("myValidation",true);
          else
            modelCtrl.$setValidity("myValidation",false);
        }
      ).catch(function() {
        modelCtrl.$setValidity("myValidation",false);
      });

    });

Feel free to check out an example on Plunker

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

Why does the onBlur event function in Chrome but fails to work in Safari?

I've encountered a problem with the onBlur event in react-typescript. To replicate the issue, I clicked the upButton repeatedly to increase the number of nights to 9 or more, which is the maximum allowed. Upon further clicking the upButton, an error m ...

Does the current protected route that I am on restrict the user from navigating back to the Home component?

I'm having trouble figuring out how to redirect the user to the Home component when they logout. The API is functioning correctly based on my tests. However, I am unsure of how to implement the logout method in the current context to successfully log ...

Receiving a reply but failing to give a response

My code is causing an ERR_HTTP_HEADERS_SENT error. Can you help me identify what's wrong with it? .then((userDetails: any) => { userDetails.role.forEach((singleRole) => { if (singleRole.name === 'admin&apos ...

Ending asynchronous tasks running concurrently

Currently, I am attempting to iterate through an array of objects using a foreach loop. For each object, I would like to invoke a function that makes a request to fetch a file and then unzips it with zlib, but this needs to be done one at a time due to the ...

What could be the issue with my JSON file?

I am currently utilizing the jQuery function $.getJson. It is successfully sending the desired data, and the PHP script generating the JSON is functioning properly. However, I am encountering an issue at this stage. Within my $.getJSON code, my intention ...

The animation-play-state is set to 'running', however, it refuses to start playing

I'm in the process of creating a landing page that includes CSS animations, such as fade-ins. Initially setting animation-play-state: "paused" in the CSS file, I later use jQuery to trigger the animation while scrolling through the page. While this s ...

What is the best way to send an email with a randomly generated HTML output using a <button>?

I am currently working on a feature where a random HTML output is sent to me via email whenever a user clicks on a button on the website page. The user receives a code when they click the button, and I want that code to be emailed to my address automatical ...

Add Content to Textbox by Clicking

In my current setup, I have a variety of buttons that, when clicked, should add the text from the button to a text box. Each time a button is clicked, I want the text to be appended to whatever is already in the input field. Current Approach $('#js- ...

Converting Excel files into JSON format with AngularJS

Seeking guidance on integrating a feature where users can upload an excel file from their device and have it converted to JSON format. Previous functionality allows for csv uploads to be converted, but now looking to enable excel conversions. Any tips or ...

Can the combination of pure HTML+JS applications with .NET webservices be both feasible and safe?

Our recent projects have utilized MVC5 with AngularJS, Ninject, Bootstrap, and various other technologies. However, we found that these applications required significant time to fix bugs and add features due to unnecessary complexity. Would it be feasible ...

Storing data on your local machine using Electron

I am in need of help with my template files which have variable strings. I want to create a basic input form using Electron (https://www.electronjs.org/) and save the resulting output file on the user's device. Could someone recommend a module that e ...

The Iron Seal feature is ineffective when a user tries to log in

Iron.seal isn't properly updating the npm module Iron, which is causing login issues for users. var obj = { a: 1, b: 2, c: [3, 4, 5], d: { e: 'f' } }; var password = 'some_not_random_password_that_is_at_lea ...

When you hit a certain point on the website, the scrolling momentarily pauses

Upon refreshing the page and scrolling down, I notice that the website experiences a brief lag for a few milliseconds before continuing as normal. Oddly enough, this issue only occurs after refreshing the page. Any suggestions on how to resolve this? Th ...

Tips for keeping a video background stationary while allowing the text to move smoothly

When I added the video for the background, it only appears at the top of the page. However, I want it to be visible as the rest of the page is scrolled. <div class="hero"> <video autoplay loop muted plays-inline class="back-video&qu ...

Struggling to send information using Angular $resource?

I've been working on sending data to an API using Angular's $resource. Currently, I can successfully retrieve data from my test server using a GET request or querying. However, I'm having trouble figuring out how to send new data to the serv ...

The website is experiencing functionality issues with Ajax

On my personal website, I am trying to add a simple ajax server clock in the header section but unfortunately it is not appearing as expected. Here's the snippet of Javascript code that I am using: var httpxml; try { // Firefox, Opera 8.0+, Safari ...

Using ASP.NET MVC, pass a list of values separated by commas to an action method

Hey there, I'm facing an issue with an ajax call where I am trying to retrieve values from an html select multiple tag. The problem arises when I attempt to pass these values into my controller as I keep getting a null reference error in my controller ...

How can I extract particular combinations from a PHP array?

I have a unique question that is quite specific and despite searching online, I couldn't find an answer. So, I decided to seek advice here. Imagine my webpage has three sliders: one for selecting color options for a square, another for a circle, and ...

The error message 'Cannot read property 'navigate' of undefined' is displayed because the function '_this.props.navigation.navigate' is not

I'm facing an issue trying to access 'Home' from Form.js. Despite my efforts in arrowF, routes, and other methods, the same error persists. How can I resolve this? In my Form.js file, when I call onPress=(), I have tried using functions, ...

Converting a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...