Utilizing $asyncValidators in angularjs to implement error messages in the HTML: A guide

This is my first major form with validations and more. I've set up a Registration form and I'm utilizing ng-messages for validation. The issue arises when I have to check the username, whether it already exists in the JSON server we are using or if it's available. If it's taken, a warning message appears in the HTML near the username input; if it's available, the submit button becomes enabled (as the form will be $valid) allowing the user to proceed with the registration process. I intend to use angular-sanitize because I discovered this snippet of code:

    ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
      var value = modelValue || viewValue;

      // Looking up user by username
      return $http.get('/api/users/' + value).
         then(function resolved() {
           // Username exists, meaning validation fails
           return $q.reject('exists');
         }, function rejected() {
           // Username does not exist, therefore this validation passes
           return true;
         });
    };

Below is the current code I am using (registration form, controller, and service):

// Controller:
export default class registerPageController {
  constructor(userService, authenticationService, $location) {
    this.register = "Register";
    this.userService = userService;
    this.$location = $location;
    this.authenticationService = authenticationService;
    this.hasLoggedIn = false;
  }

  onSubmit(user) {
    let self = this;
    let {
      name,
      age,
      email,
      username,
      password
    } = user;
    self.userService.register(name, age, email, username, password).then((res) => {
        self.userService.login(username, password).then(function (response) {
          let data = response.data;

          if (data.length) {
            let user = data[0];
            self.hasLoggedIn = true;
            self.authenticationService.setCredentials(username, password);
            self.$location.path('/');
          }
        });
      })
      .catch(err => {
        // WHAT TO PUT HERE AFTER THE USERNAME EXISTS VALIDATION ?
      })
  }
}

// Service:

export class UserService {
  constructor($http) {
    this.$http = $http;
  }

  login(username, password) {
    return this.$http({
      method: 'GET',
      url: 'http://localhost:3000/users',
      params: {
        username: username,
        password: password
      }
    });
  }

  register(name, age, email, username, password) {
    return this.$http({
      method: 'POST',
      url: 'http://localhost:3000/users',
      data: {
        name: name,
        age: age,
        email: email,
        username: username,
        password: password
      }
    });
  }

// SHOULD I PUT THE USERNAME EXISTS VALIDATION LOGIC HERE?

}
<div class="container main-content">
  <form class="registrationForm" name="registerForm" ng-submit="register.onSubmit(register.user)" novalidate="novalidate">

    <!-- Enter Name -->
    <div class="form-group">
      <label for="name" class="control-label"><span id="reqInfo">*</span> Name</label>
      <input type="text" name="name" class="form-control" ng-model="register.user.name" ng-pattern="/[a-zA-Zа-яА-Я]+/" id="name"
        required="" placeholder="Example: Petar Petrov">
      <div ng-messages="registerForm.name.$error" ng-show="registerForm.name.$touched" style="color:maroon" role="alert">
        <div ng-message="required">Your name is required</div>
      </div>
    </div>

    <!-- User Age-->
    <div class="form-group">
      <label for="age" class="control-label"><span id="reqInfo">*</span> Age</label>
      <input type="number" name="age" class="form-control" ng-model="register.user.age" ng-min="18" min="18" id="age" required=""
        placeholder="Enter your age">
      <div ng-messages="registerForm.age.$error" ng-show="registerForm.age.$touched" style="color:maroon" role="alert">
        <div ng-message="min">You must be at least 18 years old</div>
      </div>
    </div>

    <!-- Enter E-mail -->
    <div class="form-group">
      <label for="email" class="control-label"><span id="reqInfo">*</span> E-mail</label>
      <input type="email" name="email" class="form-control" ng-model="register.user.email" ng-pattern="/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/"
        id="email" required="" placeholder="Example: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6805090104280509010446060d1c">[email protected]</a>">
      <div ng-messages="registerForm.email.$error" ng-show="registerForm.email.$touched" style="color:maroon" role="alert">
        <div ng-message="required">Your valid e-mail is required</div>
      </div>
      <br>

      <!-- Enter Username -->
      <div class="form-group">
        <label for="username" class="control-label"><span id="reqInfo">*</span> Username</label>
        <input type="text" name="username" ng-minlength="5" ng-maxlength="20" class="form-control" ng-model="register.user.username"
          ng-pattern="/^[A-Za-z0-9_]{1,32}$/" ng-minlength="7" id="username" required="" placeholder="Enter your username">     
        <div ng-messages="registerForm.username.$error" style="color:maroon" role="alert">
          <div ng-message="minlength">Your Username must be between 7 and 20 characters long</div>
        </div>
        <br>

        <!-- Enter Password -->
        <div class="form-group">
          <label for="password" class="control-label"><span id="reqInfo">*</span> Password</label>
          <input type="password" name="password" class="form-control" ng-model="register.user.password" ng-minlength="7" id="password"
            required="" placeholder="Enter your password">
          <div ng-messages="registerForm.password.$error" style="color:maroon" role="alert">
            <div ng-message="minlength">Your Password must be at least 7 symbols long</div>
          </div>
        </div>

        <!-- Register button -->
        <div class="form-group">
          <button class="btn btn-primary" type="submit" ng-disabled="!registerForm.name.$valid || !registerForm.age.$valid || !registerForm.email.$valid || !registerForm.username.$valid || !registerForm.password.$valid">Register</button>
        </div>
        <p>Fields with <span id="reqInfo">*</span> must be filled.</p>
  </form>
  </div>

I have been instructed to write in ES6 specifically and I am facing issues with the logic. Please review my code and provide guidance on how to complete it so that I can use it effectively and most importantly, learn from it. Thank you very much in advance!

Answer №1

I recently created a custom directive that can handle various types of validations, both synchronous and asynchronous. It also has the capability to display warnings when needed. Feel free to take a look at it on this link:

`https://plnkr.co/2WQHOo`

If this fits your requirements and you require further details, please don't hesitate to reach out to me. I will do my best to provide answers.

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

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

The fulfillment of the post route for the login page is awaiting a request in the browser using Express Node.js

The router is currently waiting for a response (request pending) router.post('/loginpost',(req,res,next)=>{ var email=req.body.email; var password=req.body.password; var selectsql=`SELECT * FROM client WHERE em ...

Choose the specific Element by its dynamicID in JQuery

Just starting out with Jquery and I have a specific task in mind. In my HTML page, I have elements with IDs generated by concatenating a string variable. My goal is to use JQuery to select the element with this dynamically generated ID. See below for more ...

To ensure a successful redirection process without information loss, it is essential to address any potential issues with data input into

How can I properly implement a page redirection? Below are the relevant code snippets. <link rel="stylesheet" type="text/css" href="payout.css"/> <font face='calibri'> <?php session_start(); $conn = @mysql_connect("localho ...

Unable to trigger JavaScript function from ASP.NET MVC HTML view

I am encountering an issue with my ASP.NET MVC project where I am attempting to call a JavaScript function to record a user's selection from a listbox. Despite duplicating the JavaScript function in multiple places, it is still not being found. What c ...

Tips for capturing all mobile events in Angular

Trying to capture all mobile events like touch and swipe, I have added event listeners at the document level: document.addEventListener('tap', trackTouchActivity, false); document.addEventListener('swipe', trackTouchActivity, false ...

An error was encountered in compiler.js at line 1021, stating that an unexpected value 'UserService' was imported by the module 'UserModule'. It is recommended to add a @NgModule annotation to resolve this issue

As a PHP programmer new to Angular, I am facing an issue while trying to retrieve user properties from a Laravel API. When attempting this, I encountered the following error: compiler.js:1021 Uncaught Error: Unexpected value 'UserService' importe ...

How to Show a GIF in ASP.NET Core 3.0 When OnPost() is Invoked

I'm struggling to incorporate a GIF into my website, and after researching different sources, I've discovered that I need to utilize some Ajax and Javascript. However, I lack experience with both of these technologies. Is there anyone who could p ...

Getting the response from Google Cloud Translate API using Node JS

Recently, I've been experimenting with the Google Cloud Translate API in NodeJS. While I am able to successfully console.log the value returned from a promise, I am facing challenges passing that value into an EJS template file. Whenever I try to disp ...

Dealing with issues in AngularJS when a directive modifies a value within a controller

Whenever I receive large images from an API in my primary controller, a specific directive informs me of each image being loaded: app.directive('imageonload', function() { return { controller: "mainController", restrict: &apo ...

Problem with animated scrolling in Jquery

Currently, I am working on a function that aims to smoothly scroll the web to a specific div each time a user scrolls "into" a container div. You can get a better idea of what I mean by looking at my JSFiddle. Everything works perfectly when the user scro ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

Unleashing the Power of Aurelia's HTML Attribute Binding

I need to bind the "required" html attribute in my template and model. Along with passing other information like the label value using label.bind="fieldLabel", I also want to pass whether the element is required or not. However, simply using required="tr ...

Trouble Connecting Local Database with PG NPM Package

I'm encountering issues with using the pg package on my computer. I've attempted to execute the following code: var pg = require('pg'); var con_string = "postgres://user:password@localhost:5432/documentation"; var client = new pg.Clie ...

Filtering JSON Objects in JavaScript: A Comprehensive Guide

I have been attempting to filter the JSON object below and create an array of objects that have a value containing "steve" in the key 'markdown'. My initial approach involves converting the object to an array then applying a filter. Although I h ...

Is it possible to implement a Promise.some() function that includes a timeout

Scenario - collect multiple URLs and cache the responses. URLs that are processed quickly (e.g. within 500ms) are included in the current pass, while those that take longer are still cached for use in the next round (approximately 10 minutes later in our a ...

How can I increase the element by $100 using a dropdown selection in JavaScript?

Hey there! Looking to create a dropdown list with two shipping options: Special Shipping Normal Shipping <select> <option>Special Shipping</option> <option>Normal Shipping</option> </select> If the user selects Speci ...

Unable to establish a connection to the server while handling a jQuery Ajax error

I'm in the process of pinpointing an issue that occurs when submitting an Ajax request through jQuery and encountering a failed connection to the server. The scenario involves loading a page from the server, then deliberately disconnecting the network ...

Troublesome button appearance

I set up two sections to gather user information using buttons. My goal is for the button styles to change when clicked, making it clear to users which option they have selected, even if they switch between sections. However, I encountered an issue where ...