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

A guide to examining pixels in Three.js

I have a query about comparing two textures at a pixel level in three.js. I am unsure of how to achieve this as the documentation for Three.js does not provide clear answers, with some classes remaining undocumented. In summary, I am looking to determine ...

What is the best way to access the id attribute of a <td> element within a <tr> using jQuery?

Can someone assist me with this issue? Is there a way to get the ID of the first or second td element instead of using a loop? Here is an example: "<tr class='test_point' id="+fileName+"><td><img src='"+ROOT_PATH+"/assets/d ...

Change numbers into a comma-separated style containing two decimal points using javascript

I have been working on a JavaScript function to convert numbers into a comma-separated format with two decimal places: Here is my current code snippet: Number(parseFloat(n).toFixed(2)).toLocaleString('en'); The issue with this code is that it ...

The following page shrouded in mystery is experiencing technical issues

Encountering some issues on the live server with this code. It's functioning perfectly fine on my local machine, but once I try to deploy it on Netlify, I'm running into this error message: ⨯ useSearchParams() should be wrapped in a suspense bo ...

Modify mouse pointer when an object is clicked using JavaScript

Greetings, I am in the process of designing a website for a client. I have encountered a challenge in changing the cursor icon when a user performs a mousedown on an object. There is an image on the webpage When the user clicks on the image, the cursor s ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

What could be the cause of a JSON string only returning the final object when evaluated?

Does anyone have insight into why only the last object in my json string is returned when I use the eval function? ...

Adjust the color of the text as it scrolls by

As I work on developing my website using the Neve Theme on WordPress, I have encountered an issue with customizing the header block. I am using a plugin to set a background color for the header after scrolling 100px down the page, but this makes the text h ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

Forced line break at particular point in text

I would love to implement a line break right before the "+" character, either using css styling or through a different method. Is this task achievable? #myDiv{ width: 80% } #myP{ c ...

Preventing Time Limit Reset on Page Refresh with Jquery/Javascript

I'm encountering an issue with the time limit on my online quiz program. Whenever the page is reloaded or refreshed, the time limit resets. I have implemented this time limit in my online quiz program using a PHP header('Location:') to prog ...

Customizing Django forms.Textarea in template or declaring in models is essential for creating a unique

Within my models, I have a forms.Form that includes a textarea field: answer1 = forms.CharField(label='Answer 1', widget=forms.Textarea(attrs={"placeholder":"Type your answer...", "rows":6, "cols":45}), max_length=150) When it comes to views: ...

ajax is triggering the error handler

I am currently developing a web application and I am trying to send data from a PHP controller to JavaScript. After conducting some research, it seems that the most efficient way to accomplish this is by utilizing Ajax and Json. However, I am encountering ...

D3: Ensuring Map is Scaled Correctly and Oriented Correctly

I am attempting to integrate a map into a website using D3 and topoJSON that resembles the following: However, when I create the map with D3/topoJSON, it shows up small and inverted. Even after exploring various solutions (like Center a map in d3 given a ...

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...

JavaScript's sequential addition of nested arrays

Having trouble adding together 4 nested arrays in JavaScript. The arrays are structured like this: x = [[Array1(9)], [Array2(9)], [Array3(9)], [Array4(9)]] I am looking to "zip" them together and add the values. For example, I want to add Array1[0] with c ...

AngularJS: How to detect when the user has scrolled to the bottom of a div and trigger an event?

I am attempting to trigger an event when the scroll bar reaches the end. After searching, I came across this example. Below is my code, however, it seems that the loadmore() function is not being called at all. The console statements display the following ...

Using the i18next Module for Localization in ExpressJS and Front-End Development

I am currently integrating the i18next module into my NodeJs/ExpressJS web application. All the translation files are stored in the /locales directory. According to information from i18next.com, it can also be utilized on the client side. <script typ ...

Ways to modify the header color of a card by utilizing a Select element in Javascript, while ensuring that it does not impact other cards

I am facing an issue with multiple cards, each containing a Select element. When a user selects an option from the Select element, the card header changes color, but it also affects all other card headers. How can I separate them? [data-background-co ...