Observing the CSS class of an input element during async validation does not yield the desired results

Recently, I implemented a bootstrap directive that monitors all the input elements on a form and updates the CSS of its parent div to display validation errors in a Bootstrap-friendly manner. The directive checks for the presence of the ng-invalid class in the elements' CSS and adds has-error to the parent if found.

element.find('.form-group').each(function () {
    var formGroup = $(this);
    var inputs = formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
    if (inputs.length > 0) {
        inputs.each(function () {
            var input = $(this);

            scope.$watch(function () {
                return input.hasClass('ng-invalid') && (!input.hasClass('ng-pristine') || form.$submitted);
            }, function (isInvalid) {
                formGroup.toggleClass('has-error', isInvalid);
            });
        });
    }
});

The initial concept of this directive was borrowed from an answer on S.O., possibly originating from Reconcile Angular.js and Bootstrap form validation styling, although it went through further enhancements by another contributor whose specific modifications I couldn't locate. In addition, aspects of the code were inspired by show validation error messages on submit in angularjs for handling form submission prevention but I haven't included that functionality here.

While this directive functions smoothly with synchronous validators, it encounters issues with async validators where the validation states become muddled. Upon marking a field as invalid, the watch triggers, however, input.hasClass('ng-invalid') erroneously returns false. This discrepancy leaves me perplexed regarding its root cause.

I've set up a plunkr demonstration available at http://plnkr.co/edit/0wUUPdZc0fYN6euvsIMl?p=preview

Answer №1

One possibility to consider is implementing child forms for every form group. If any of the child forms are deemed invalid, then the parent form would also be considered invalid.

For illustration purposes, you can check out this example: http://jsbin.com/luvegecalo/1

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

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

Error encountered when attempting to send JSON data with special characters via a POST or PUT request using node.js's http.request()

While attempting to use the node.js http module to PUT a JSON data into CouchDB, I encountered an issue. The JSON included a special character "ä" which caused CouchDB to respond with an "invalid_json" error. However, once the special character was remove ...

Utilize Vuex mutators within route navigation guards

Hey there, I'm currently working on an app using Laravel and VueJS. To restrict certain routes, I've implemented navigation guards. However, I'm facing an issue where I need to access Vuex mutators to determine if the current user is logged ...

Creating a pop-up effect for a div in the center of a table cell using HTML and CSS

I am currently working with Angular and facing a challenge where I need to display a div like a popup in a table cell when clicked. Despite having the click event logic in place, I am unsure of how to achieve this without using external libraries such as B ...

Passing variables with AngularJS and Typescript using a service

Currently in the process of developing an application using AngularJS, I am faced with the challenge of passing a URL when clicking on a menu button in order to utilize that URL within an iframe on another view controlled by a separate controller. Despite ...

AngularJS is successfully retrieving the JSON file, but it is failing to display the data

Currently, I am working on a small AngularJS (1.6.6) website where I am retrieving data from a local JSON file within my projects.js component, not the main/index js file. Even though I can see the JSON array in the console when I use console.log($scope.pr ...

Unable to access a frame inside an iframe and frameset using JavaScript when both domains are identical

I am attempting to use JavaScript to access an HTML element within a nested frame in an iframe and frameset. The structure of the HTML is as follows: <iframe id="central_iframe" name="central_iframe" (...)> <frameset cols="185, *" border="0" ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...

The static folder in Express server is failing to serve files

I have an application with certain static files that I want to send to the client, however the server is not sending them. app.use(express.static(__dirname, '/public')); I need help fixing this particular code snippet. ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Determine the total number of hours along with the precise minutes

Could you assist me with calculating minutes? Here is an example: var time_in = '09:15'; var break_out = '12:00'; var break_in = '13:00'; var time_out = '18:00'; var date = '2018-01-31'; var morning = ( ...

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

unable to assign values to this.props (appears as undefined or an empty array)

Upon setting up react/redux, I encountered a peculiar issue. When my component mounts, it should render the information stored in this.props.heroes.data. However, upon logging this data, I receive an unexpected value of [{id:1,heroname:'Batman',r ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

angular ensuring seamless synchronization of objects across the application

This question pertains to both angular and javascript. In our angular app, we have numerous objects from the backend that need to remain synchronized. I am facing challenges in establishing efficient data bindings to ensure this synchronization throughout ...

Obtain the popup URL following a fresh request using JavaScript with Playwright

I'm having trouble with a button on my page that opens a popup in a new tab. I have set up a listener to capture the URL of the popup when it opens: page.on('popup', async popup => { console.log('popup => ' + await pop ...

The error message "Unexpected token var Node.js" means that there is a syntax error

Currently, I am dealing with Node.js and attempting to present a chart that is created from coordinates in a txt file uploaded to the server. However, I am facing an issue where everything works perfectly when I upload the file on the web page except for t ...

Troubleshooting: "Go To Definition" Feature in VS Code Fails to Work When Imports are Without Path

I am currently configuring VS Code to enable me to navigate to definitions by cmd+click or right click + Go To Definitions when importing JS components that do not use relative or absolute paths. These components are set up by Webpack to search for any fil ...

Error: The identifier has already been declared and cannot be re-declared

I am attempting to create a modal-cookie feature that will display a modal on page load if a cookie named "name" does not exist. However, I encountered an error: Uncaught SyntaxError: Identifier 'addCookie' has already been declared. This erro ...

Encountered a server error while trying to export from Content

I'm attempting to retrieve data from a specific space in Contentful by utilizing the https://github.com/contentful/contentful-export npm package. However, when I execute my code following the example provided on the GitHub page, I encounter the follow ...