Validating input in AngularJS with custom rules based on a resource

In my Angular application, I have a form that undergoes custom validation on all fields whenever there is a change in any field. This means that the validity of each field can change based on the values of other fields in the form, resulting in the entire form being validated with every edit.

Although the validation functions correctly, I am facing an issue where the form field being edited loses focus every time the validation is triggered (such as with each key-press). I suspect that this problem is due to a flaw in the validator implementation that I had copied from the internet months ago and now can't locate.

This issue occurs specifically in Chrome, but not in IE9.

Here is the snippet of the implementation. Can anyone spot any obvious mistakes that could be causing the focus problems I am experiencing?

angular.module('myComponent').directive('myValidator', function (MyApiResource) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, ele, attrs, ctrl) {
            function myValidator(value) {
                if (value) {
                    var myObject = JSON.parse(JSON.stringify(scope.myObject));
                    myObject[attrs.name] = value;
                    MyApiResource.validate(myObject, function (uiValidationFailures) {
                        for (var attributeName in myObject) {
                            if (scope.correctionForm[attributeName]) {
                                var valid = !uiValidationFailures.filter(function (el) { return el.AttributeName === attributeName; }).length;
                                scope.correctionForm[attributeName].$setValidity('myValidator', valid);
                                if (valid && attributeName !== attrs.name && scope.correctionForm[attributeName].$pristine) {
                                    scope.correctionForm[attributeName].$setViewValue(myObject[attributeName]);
                                }
                                scope.uiValidationFailures[attributeName] = valid
                                    ? undefined
                                    : uiValidationFailures.filter(function (el) { return el.AttributeName === attributeName; });
                            }
                        }
                        return value;
                    });
                    return value;
                }
                scope.uiValidationFailures[attrs.name] = undefined;
                return undefined;
            };
            ctrl.$parsers.unshift(myValidator);
            ctrl.$formatters.unshift(myValidator);
        }
    }
});

Answer №1

Although I don't see any issues in your code (without more information), there is a red flag when you mention

The issue is happening in Chrome, but not in IE9.

Additionally, you're referring to a form field losing focus. My suspicion is that there may be some inconsistencies - potentially in the focus behavior? - between the two browsers. It's likely not a JavaScript problem.

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

Having trouble integrating Twilio into your Meteor app? Getting a ReferenceError that says "Twilio is not defined"?

Let me start by saying that I'm new to Meteor and Twilio, so it's likely that I've overlooked something simple. I'm utilizing the Twilio API bindings from this source in an attempt to send an SMS message within a Meteor.methods functio ...

Can we bring flexbox inserts, removes, and item positioning to life through animation?

This question was first raised in 2012, but the responses provided didn't address my specific situation (smooth transition for rearranging wrapped content). "After removing an item from a flexbox, the remaining items snap into their new positions imm ...

Numerous error notifications triggered by a different data field

I attempted to create a dynamic error message: window.Parsley.addValidator('validatorName', { requirementType: 'string', validateString: function (value) { return validateField(value); }, messages: { en: &apo ...

Conceal an absolutely positioned element outside its relatively positioned parent

I have a relative position parent element, <div style="position:relative" id="a"> and within that div, I'm creating some absolute positioned elements using jQuery, <div style="position:absolute;right:0" id="b"> These elements are anima ...

Dynatree fails to consider the select feature while utilizing ajax requests

Currently, I am utilizing the dynatree plugin to exhibit a checkbox tree in multi-select mode (mode 3). Upon initializing the tree using ajax (without lazy loading), it appears that certain nodes that were initially loaded as selected are forgotten. When ...

Leverage the power of AngularJS to seamlessly incorporate and utilize dynamically generated HTML within the

Encountered an issue trying to dynamically add generated HTML to the controller's scope and utilize it. I previously posted about a similar topic (generated AngularJS controller usage), but the current task is slightly different now (no need to genera ...

Utilizing Fragments in Vuejs 2.x with Jsx - A User's Guide

Considering the presence of Fragments in React and the lack of a specific solution in the official Vuejs GitHub thread, what alternative methods could be used in Vuejs? This information may be beneficial for developers transitioning from a React backgrou ...

Developing a custom function that analyzes two distinct arrays and sends any corresponding pairs to a component

I'm in the process of developing a component that utilizes two arrays. These arrays are then mapped, and the matching pairs are sent down as props to a child component. The goal is to create a list component that retrieves the arrays from the backend ...

Checkbox malfunctioning when trying to add values after being checked

I have successfully completed a calculation system project using JavaScript. Everything works well, the calculations are accurate and taxes are included properly. However, I am facing an issue where the tax is not being included when I click on the checkbo ...

The behavior of AJAX Search varies between the development and production environments

I recently integrated an instant search feature into my application. During testing on the local server, the functionality met my expectations: It filters the list as I type It is not case-sensitive It allows for resetting the search if I delete the inp ...

How can the top height of a jquery dialog be reduced?

Just starting out with jquery, I've got a dialog box and I'm looking to decrease the height of this red image: https://i.sstatic.net/BuyQL.png Is there a way to do it? I've already made changes in the jquery-ui.css code, like so: .ui-dia ...

The color overlay for the class label map segmentation in AMI JS is not appearing as expected

I came across this example in vanilla JavaScript. In my project using Angular 7.3.8 with AMI version 0.32.0 (ThreeJS 0.99.0), I imported everything as an angular provider service. When trying the test examples from the provided link, I noticed that the o ...

Using Firefox to cache Ajax calls after navigating back in the browsing history

Currently, I am utilizing an ajax call to invoke a php script that waits for 40 seconds using sleep and then generates the output RELOAD. Subsequently, in JavaScript, the generated output is validated to be RELOAD, following which the call commences again. ...

Tips for adjusting the font size of the xdsoft calendar datetimepicker

Looking to enhance the appearance of my jQuery calendar within my HTML template with the help of this resource. I've identified that adjusting the font-size is crucial for increasing the size of the calendar. <script> $(function () { $(&qu ...

What is the optimal parameter order when utilizing pre-curried functions and composition in JavaScript?

We have a simple, mathematically curried function for subtracting numbers: function sub(x) { return function (y) { return x - y; }; }; sub(3)(2); // 1 The function signature matches the obtained result. However, when function composition comes i ...

Why is ng-click not triggering within ng-repeat?

I currently have the code snippet below: scope.monthpickerclick = function(scope){ $window.alert('test'); console.log(scope); }; scope.monthpicker = function(alldatesdumparray){ var alldatesdump = booking.getalldates(); var ...

Tips for displaying tooltips with values that are constantly updating

I am seeking a solution to display tooltips when hovering over a textarea with changing values. The user has the ability to input lengthy text, and I would like the tooltip to show the updated data. Any suggestions on how this can be achieved? ...

Discover the inner workings of Angular Universal with Angular 11 by exploring the page source

Attempting to update the script type application/ld+json src in Angular Universal after user actions. const newScript:HTMLScriptElement = document.createElement('script'); newScript.setAttribute('type', 'application/ld+json') ...

Is it necessary to conceal the element every time the jQuery slideDown function is utilized?

Previously, I inquired about a certain matter related to this topic, but the response I received didn't provide a clear explanation. When pressing the 'duplicate' button on my form, instead of the input field simply appearing, I would prefe ...

What is the method employed by the script to ascertain the value of n within the function(n)?

I've recently started learning about jQuery. I came across a program online that uses a function where the value of n starts from 0 and goes up to the total number of elements. In the example below, there is only one img element and jQuery targets thi ...