Checking the availability of AngularJS usernames

I am facing an issue with the directive meant to verify username availability. Despite getting a response from the server, the form continues to disable the submit button.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, $http) {
  $scope.name = 'World';

});
    myApp.directive('verifyStore', function($timeout, $q, $http) {
      return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) { 
          model.$asyncValidators.usernameExists = function() { 
            //here you should access the backend, to check if username exists
            //and return a promise
             return $http.get('/api/verifystore').then(function(res){
              $timeout(function(){
                model.$setValidity('usernameExists', true); ---> or false button still disabled
              }, 1000);
            }); 
          };

        }
      } 
    });

    <div class="form-group">
        <input type="text" verify-store ng-model="storename" class="form-control" name="merchant.store_name" placeholder="Store Name" ng-model-options="{ updateOn: 'blur' }" required>
        <div ng-if="signupForm.$pending.usernameExists">checking....</div>
        <div ng-if="signupForm.$error.usernameExists">username exists already</div>
        </div>

The Submit button

<button type="submit" ng-disabled="signupForm.$invalid" class="btn btn-primary pull-right">
                            Submit <i class="fa fa-arrow-circle-right"></i>
                        </button>

Thank you for your help!

Answer №1

Make sure to fulfill your promise if the username does not already exist.

     model.$asyncValidators.usernameNotExists = function() { 
         return $http.get('/api/checkstore').then(function(res){
             return res ? res : $q.resolve('username is available');
         }); 
      };

Source: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$asyncValidators

Answer №2

If your server accepts the username, you need to fulfill the promise by returning true. However, if the username already exists, as mentioned by TKrugg, you must reject the promise.

Check out this helpful demo on Plunker. Instead of using the $timeout service, make a direct call to your server.

app.directive('verifyStore', function($timeout, $q, $http) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) { 
            model.$asyncValidators.usernameExists = function(modelValue, viewValue) {
                // Access the backend here to check for existing usernames and return a promise
                return $http.get([yourUrl]).then(function(response) {
                    if (!response.data.validUsername) {
                        return $q.reject(response.data.errorMessage);
                    }
                    return true;
                });
            };
        }
    };
});

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 functionality of the OnClientClick event within the ASP.NET platform

While utilizing ASP.NET to pass a value to a JavaScript function, I encountered an issue where it doesn't seem to work when trying to pass a value from another control. It seems to behave as if there is a syntax error and just reverts back to the main ...

How to retrieve a Typescript variable within an ngIf conditional statement in Angular

How can I access a TypeScript variable inside an ngIf statement? TS: public data: string; HTML: <td> <div *ngIf="data === 'BALL' ; else noplay" >{{ play }}</div> <ng-template #noplay> {{ gotohome ...

AngularJS: Incorporate a loading spinner at the beginning of the document object model

After spending some time searching for the best way to accomplish this task without any luck, I am starting to doubt my search skills or perhaps no one has posed this question before. Despite leaning towards the former, I still find myself at a dead end. ...

"webpack" compared to "webpack --watch" produces varying results in terms of output

My project is built on top of this setup: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html Running webpack compiles a bundle that functions correctly in the browser. However, running webpack --watch to recompile on file changes resul ...

Encountering a mistake due to the anticipated atom not being found at the specified

In my react application, I am encountering an issue with allowing foreign characters along with English in the input field of a form. I have implemented a regular expression as follows: const alphabetRegex = /^([A-Za-z]+ )+[A-Za-z]+$|^[A-Za-z]*\p{L}/g ...

Material UI AppBar displaying custom colors instead of theme colors

Currently, I am utilizing Material UI version 4.7.0. In my project, I have established a customized theme (shown below) by utilizing createMuiTheme() method with personalized primary and secondary colors set. Within my AppBar component (also displayed be ...

Tips for testing a function that calls other functions during unit testing

Exploring jest for the first time to test my REST API has been quite the learning experience, especially when it comes to unit testing the controllers. I'm facing a challenge in testing a function that involves calls to other functions (including npm ...

Guide on executing dynamic queries with MySQL in Meteor

Attempting to execute dynamic queries against MySQL in Meteor using the numtel:mysql package has proven unsuccessful thus far. It seems that either I need guidance on passing dynamic arguments to the subscribe function, or I need to learn how to retrieve ...

Encountering Error with NodeJS Typescript: Issue with loading ES Module when running sls offline command

I have come up with a unique solution using NodeJS, Typescript, and Serverless framework to build AWS Lambdas. To debug it locally in VS Code, I use the serverless-offline library/plugin. You can find my project on GitHub here However, when I run the comm ...

Utilizing JavaScript variables to generate a custom pie chart on Google

Greetings! I must admit that I am a novice, especially when it comes to JavaScript. My background is mainly in PHP. Recently, I came across a fantastic pie chart created by Google https://developers.google.com/chart/interactive/docs/gallery/piechart I a ...

having difficulty preserving the edited HTML document with JSoup and Java

I am facing an issue with modifying and saving changes to an existing HTML file. I can make modifications, but when it comes to saving the changes back to the HTML file, I encounter difficulties. https://i.sstatic.net/CRhUV.jpg The specific modification ...

Loading objects with textures in Three.js using the objloader

For the past few weeks, I've been diving into Three.js and managed to successfully apply a texture to a cube I created directly in the code. However, when I attempted to load an OBJ file using OBJLoader, I ran into issues trying to load simple png or ...

Ways to incorporate JavaScript code within Reactjs

I am currently working with Reactjs and using Nextjs. I am facing a challenge regarding integrating "index.html" with "index.js". At the bottom of "index.html", there is some JavaScript code that I need to transfer to another file. Can you advise me on w ...

Encountering a SyntaxError due to a lexical declaration that is not allowed within a single-statement context

I encountered an issue with the 'let' part of my code. After some troubleshooting, I discovered why the bot wasn't starting - moving the client.login to the end fixed it. However, a new error has cropped up where the bot keeps spamming "Inva ...

Utilizing the getJSON Method to Automatically Fill a Dropdown Selection Element

I am looking to populate a dropdown select menu with bank names and IIN numbers obtained from the following JSON: JSON Data : {"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Ba ...

Changing in height by utilizing javascript's style.height animation

When attempting to adjust the height property using JavaScript instead of jQuery, a challenge arises. The issue lies in the inability to reset the height back to zero after setting it to the scrollHeight of the element. The following is the JavaScript cod ...

Convert a fresh Date() to the format: E MMM dd yyyy HH:mm:ss 'GMT'z

The date and time on my website is currently being shown using "new date()". Currently, it appears as: Thu May 17 2018 18:52:26 GMT+0530 (India Standard Time) I would like it to be displayed as: Thu May 17 2018 18:43:42 GMTIST ...

React-Native Error: Invalid element type detected

While attempting to run my React Native app on my iPhone using Expo, I encountered an error displayed in a red background area. Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

The issue of the DNN ModuleID not being effectively communicated from the code behind to the ascx component is

Background: I am utilizing a DNN (DotNetNuke) content management system to support VB.NET/Angular1 modules. Currently, I am facing an issue where a value in the code-behind is not accessible in the View.ascx of my module, resulting in a critical runtime e ...

Challenges with server side JavaScript in Nuxt.js, causing confusion with the framework

My partner and I are embarking on a website project for our school assignment, and we have opted to utilize Vue.js and Nuxt.js as the front-end frameworks, along with Vuesax as our chosen UI Framework. Despite our lack of experience with these tools and we ...