Utilizing Asynchronous Multifield Validation at the precise moment before the validation data is confirmed

In the current project I'm handling, there is a straightforward dialog for adding a custom employee to a business application. The modal includes basic fields like first name, last name, OK, and Cancel. Seems simple enough, right?

However, one of the key rules in place is that duplicate employees cannot be submitted. To address this rule, I have integrated an angular directive as follows:

(function() {
    'use strict';

    angular.module('app').directive('checkDuplicateEmployee', ['$q', 'officesSvc', 'webDataSvc', directive]);

    function directive($q, officesSvc, webDataSvc) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, elem, attrs, vm) {
                vm.$asyncValidators.duplicateEmployee = function (modelValue, viewValue) {
                    // Issue detected here!
                    var args = {
                        officeType: officesSvc.officeType,
                        officeName: officesSvc.selectedOffice.name,
                        firstName: scope.vm.firstName,
                        lastName: scope.vm.lastName
                    };

                    // Custom $http wrapper.
                    return webDataSvc.get('/api/admin/DoesEmployeeExist', args)
                        .then(function(results) {
                            if (results === true)
                                deferred.reject(results);

                                return true;
                            });
                };
            }
        }
    }
})();

The problem arises when I apply the directive to an input field...

<input type="text" id="firstName" name="firstName"
       maxlength="35"
       ng-model="vm.firstName"
       required check-duplicate-employee />

After entering text, what gets sent to the server is actually the state before my most recent keystroke.

Field:      | vm.firstName:      
----------------------------
T           |
Te          | T
Tes         | Te
Test        | Tes

This situation reveals that the scope doesn't update until after the validation process occurs.

My Question: Is there a way to perform asynchronous validation after the $scope.vm object has fully updated? Keep in mind, simply passing the viewValue to the firstName property in the arguments list isn't a feasible option due to having the same validation process on both the vm.firstName and vm.lastName properties!

Answer №1

By a stroke of luck, there happens to be a way to access the view values!

The process of angular form validation involves attaching things to the scope. This includes the controllerAs alias and the form object. If we have named our form as employeeModal, then we can retrieve it from a link(scope) function by using scope.employeeForm.

Forms contain properties for each input with a name attribute (e.g. scope.employeeForm.firstName). These properties include a $viewValue property that allows manipulation of the view value.

Therefore, some adjustments to the directive are necessary. Specifically, one must A) identify the name of the form object, and then B) traverse the scope to access the desired element's $viewValue and incorporate it into the parameters of the remote validation.

link: function(scope, elem, attrs, vm) {
    var formName = $(elme).parents('form').attr('name');

    vm.$asyncValidators.duplicateEmployee = function () {
        var args = {
            officeType: officesSvc.officeType,
            officeName: officesSvc.officeName,
            firstName: scope[formName].firstName.$viewValue,
            lastName: scope[formName].lastName.$viewValue
        };

        // Perform remote validation call.
    };
}

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

Using an array as a reference can lead to failure when dealing with asynchronous calls

As I delve into referencing a document in MongoDB, my process involves first creating the document to insert before interfacing with the database itself. Upon initial setup: const venues = [ new Venue({ name: 'A' }), ]; const events = [ new ...

Is there a specific location to view the output when adding a console.log in vue.config.js?

Currently, I am utilizing the Vue cli 3 UI for my latest project and am faced with a challenge regarding modifying variables within a webpack plugin. Initially, my first thought was to use console.log; however, I am uncertain of where the output would be ...

What is the reason that this particular JQuery code is malfunctioning in the IE browser once integrated into my website?

Currently, I am utilizing the DDCharts jQuery plugin from DDCharts JQuery to incorporate some charts into my website. After downloading the plugin and testing it in various browsers, I encountered an issue specifically with Internet Explorer 8+. Strangely, ...

When a user clicks on the product id field, I would like to add my data underneath the table and then conduct a search

When adding data to a table, I noticed that it is being added at the top instead of below the table, I implemented a search feature where the user can enter a product id, but I cannot seem to locate the error in my code, Is there a way to add a search fiel ...

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

Completion of the form within the Bootstrap popover

I have a feature where dynamically created rows contain an "add" button. When the user clicks on the add button, a form is loaded into a Bootstrap popover. See FIDDLE DEMO My issue is: Why isn't this code being triggered? I am trying to validate ...

The use of the CSS property overflow:hidden results in certain child components being hidden, even when moved back into the visible

At the top of my screen, I have a message box banner styled as follows (I'm using React + Material UI): style={{ display: "flex", flexDirection: "row", justifyContent: "flex-start", textAlign: "left ...

Issues with sending empty strings to an API in Vue Js

My code below is designed to update data using a Node Js REST API. The remaining field contains an equation using v-model=remaininginst to calculate and store the result in remaininginst. However, when I check the console.log, I am getting NaN empty data s ...

Tips for sending values as parameters to a function within an onclick event in Angular2 without using ngClick

In my Angular2 project, I am facing an issue with passing values from an *ngFor loop as a parameter to a function call on the (click) attribute event in my anchor tag. This is because calling functions using onclick is not allowed for security reasons. He ...

Setting the height of Material-UI TreeView

Looking for advice on how to set a fixed height or dynamically adjust the height of a material-ui TreeView to fit the display? https://i.sstatic.net/40Qlv.png I'd like a scrollbar to appear when the TreeView content reaches a height of 100 pixels, f ...

Automated validation and submission within an Adobe PDF document

After clicking the "submit" button on my PDF form, I want to perform a specific action (such as making a field readonly) based on whether the form validation and submission processes are successful: if (form.isValid()) { submitForm(...); if (form. ...

Utilizing a jQuery click event to modify the placement of a table

I have a request regarding the tables within the #middlebox. I would like to be able to rearrange the table positions by clicking on the list items. For instance, if the current order of the tables is starter -> soup -> seafood, clicking on the #seaf ...

Having trouble executing partial views with node.js and AngularJS?

I have been working on my AngularJS application and everything functions correctly when I browse it. However, I've encountered an issue while trying to configure Express. The main page displays fine, but when I click on the hyperlinks to load partial ...

Unable to delete element from the given array

I have been working on removing instances of 'store.state.location.locations' from my locationData array that should no longer be there, but for some reason, they are persisting in the array even though I am no longer passing those instances. ta ...

Filtering an array of parent elements in Javascript based on a specific value found in

Trying to filter data from a 3-layer array based on child array values. Making progress but hitting a roadblock at the end. { "id": 1, "grandparent": "Timmy", "parents": [ { "id&q ...

JavaScript date parsing with the Central European Time (CET) as the default timezone

Dealing with legacy webservices that inconsistently localize dates can be challenging. Sometimes the dates include timezone information, but other times they do not. In this case, I need to accommodate both scenarios. The requirement is for the dates to a ...

Show another div once you've scrolled beyond the first

Instead of following tutorials that make a div appear after scrolling down a set number of pixels, I am looking to achieve something different. I want a div to appear when the user scrolls past another div, and then disappear again when they scroll back up ...

Processing multipart form data in a Node.js Express application

I am encountering an issue with sending form data from a reactjs app using axios. Even though the express is properly configured, the req.body appears to be empty. What could be causing this problem? import bodyParser from 'body-parser'; app.use ...

How can I utilize inline jade.render() in Express with Jade template engine?

I am facing a challenge while attempting to utilize another team's jade template with Node's Jade. The template is quite intricate, featuring numerous mixins and other components. I have encountered an issue within one of the mixins that prevents ...

Using Switch Case and If Statements in Javascript and Jquery

Can you help me troubleshoot this code? It's designed to detect clicks and keypress events within the #ts_container div for buttons and anchors. The goal is to use an If statement in each case to determine if it's a click or keypress, then update ...