The perplexing quandary of validating email uniqueness in AngularJS

My form in Angular needs to be able to detect duplicate user emails.

The code I'm concerned about can be found here: http://plnkr.co/edit/XQeFHJTsgZONbsrxnvcI

This code includes the following directives:

  • ngFocus: tracks whether an input is on focus or blur, and uses a variable hasVisited to only validate the input on blur if it has been reached by the user at least once.
  • emailUnique: compares the email entered with an existing hardcoded email to determine if it's valid.

To see the field validation error, make sure to press the "tab" key to trigger the blur function.

  • If I leave the email input empty and move to the Name input (to blur the email input), it shows: The field is required. That's working as expected.
  • If I enter an invalid email like "ferfergre", it displays: This email isn't valid.. That's also working correctly.
  • If I then enter a valid email different from the hardcoded one: ([email protected]), no error is displayed which is correct.
  • If I enter the existing email: [email protected], it shows: This email already exists.. This warning is necessary.
  • However, if an email has been flagged as existing during the DOM cycle, even if I change it to a new valid one, the error remains...

Question: How can I handle this last case?

I have two hypotheses:

  • The order of HTML attributes might play a role:
    autofocus email-unique ng-focus required
  • The setValidity method in the emailUnique directive could prevent ctrl from being $valid again, thus stopping the email comparison from running again.

Answer №1

To fix your parser function, simply exclude the following snippet:

if(!ctrl.$valid){
    return viewValue;
}

This specific code was causing the email comparison to not be triggered.

If you keep this snippet, the comparison code below it will only execute when the control is valid and will never run if the control is invalid.

For an improved solution, consider the following:

If you prefer to skip the comparison when the email field is not valid based on other rules like "required" and "email", then also check for ctrl.$error. Instead of removing the previous snippet, modify it as follows:

if(!ctrl.$valid && !ctrl.$error.emailUnique){
    return viewValue;
}

This adjustment ensures that it only returns when the control is invalid due to rules other than email uniqueness.

Updated plunker: http://plnkr.co/edit/IDQitVkeHHDyJlcsatMy?p=preview

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

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = Objec ...

How can you determine in Chrome when the content of an iframe has been modified by using document.write?

When working with iFrames in different browsers, there can be challenges. For example, in Internet Explorer (IE), we can effectively use the onreadystatechange event to track changes in an iFrame's content when using document.write. However, this meth ...

Dynamic matching of variables being passed to a directive

My latest coding project involved creating a custom directive for managing HTML images, making it easier to store and display URLs and alt tags. By using a specific value via the data field (referred to as data-type in the code), I can effortlessly replace ...

Mastering the Art of Disabling buttons in Vue Based on Conditions

In my current project, I'm attempting to compare specific values of an initial object with an updated object in order to disable a button if they are the same. However, despite making changes, the button remains disabled: setDisabled() { return th ...

How come my data is not appearing on the screen despite receiving a result in the console log?

I am facing an issue with displaying data obtained from Supabase. I am passing the data as a prop and using map to iterate over it in order to show the required values. However, despite logging the correct results for `programme.title`, nothing is being re ...

Step-by-Step Guide on Resetting Versions in Package.json

I currently have around 20 react projects, each with their own package.json files. These package.json files contain various packages and their versions: "@material-ui/core": "4.11.4", "@material-ui/icons": "4.11.2", ...

Using Angular routing without relying on a web server to load templates

Can templates be loaded in Angular without a web server? I came across an example here: https://groups.google.com/forum/#!topic/angular/LXzaAWqWEus but it seems to only print the template paths instead of their content. Is there a functioning example of t ...

Creating a foolproof image polling platform: A step-by-step guide

I'm in the process of creating a webpage on my site that allows users to view a collection of images. The goal is for each registered user to choose one picture as their favorite, increasing that picture's score by one. The image with the highest ...

A Step-by-Step Guide to Setting Up and Utilizing V-Calendar in Vue.js

I am currently trying to incorporate the V-Calendar library into my Vuetify application. Up until now, the app was working fine, but I seem to have hit a roadblock with the correct installation of the V-Calendar library. Although no error messages are bei ...

What is the best way to start data in an Angular service?

I'm currently navigating my way through building my first Angular application. One of the services I am using needs to be initialized with a schema defined in its constant block, but the schema/configuration is not yet finalized. Therefore, I am perfo ...

Retrieve a value using the jQuery each() method

Hello, I am a beginner in JavaScript and I need help with extracting values from JSON and adding them to an array. My goal is to be able to parse this array using another function later on. However, I'm struggling with returning the array after adding ...

What is a more efficient way to write nested subscribe in Angular?

I am a beginner with RxJS and I'm interested in learning how to write clean code using it. I currently have a nested subscription that I've been trying to refactor without success. firstMethod() { this.testMethod(name) console.log(this.curren ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...

Inject() in AngularJS and Jasmine triggers an error

Recently, I've been working on writing tests using karma and jasmine. Take a look at this code snippet: describe("users module", function(){ var scope, controller; beforeEach(function () { module('users'); }); it( ...

Issue encountered with the Selenium JavaScript Chrome WebDriver

When it comes to testing an application, I always rely on using Selenium chromewebdriver. For beginners like me, the starting point was following this insightful Tutorial: https://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started After download ...

What impact does setting a variable equal to itself within a Dom Object have?

Within my code example, I encountered an issue with image sources and hrefs in a HTML String named tinymceToHTML. When downloading this html String, the paths were set incorrectly. The original image sources appeared as "/file/:id" in the String. However, ...

jQuery Mishap - Creating an Unspecified Issue

At the moment, my website displays a list of registered users in one column and their email addresses with checkboxes next to them in another column. Users can check the boxes and then click a submit button to generate a list of the selected emails separat ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...