The ngMessages validation feature in AngularJS fails to remove error messages from the CSS styling

Can anyone help me figure out why I keep getting a red color underline error even though there is no actual error and validation is successful?

https://i.sstatic.net/AESLl.png

I created my own directive to validate passwords and I am using Angular material.

For the working code, click here: http://codepen.io/anon/pen/gPrMRM

Here is the Angular app and JS:

angular.module('MyApp', ['ngMaterial', 'ngMessages'])

.controller('AppCtrl', function ($scope) {
    $scope.project = {
        description: 'Nuclear Missile Defense System',
        rate: 500
    };
})
.directive('validPasswordC', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (viewValue, $scope) {
                var noMatch = viewValue != scope.projectForm.password.$viewValue;
                scope.projectForm.password.$error = {};
                ctrl.$setValidity('noMatch', !noMatch);
                console.log("scope.projectForm.password.$error: ");
                console.dir(scope.projectForm.password.$error);
            })
        }
    }
});

In the HTML:

<div ng-controller="AppCtrl" layout="column" ng-cloak="" class="inputdemoErrors" ng-app="MyApp">
    <md-content layout-padding="">
        <form name="projectForm">
            <md-input-container class="md-block">
                <label>Client Email</label>
                <input required="" type="email" name="clientEmail" ng-model="project.clientEmail" minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/">
                <div ng-messages="projectForm.clientEmail.$error" role="alert">
                    <div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
                        Your email must be between 10 and 100 characters long and look like an e-mail address.
                    </div>
                </div>
            </md-input-container>

            <md-input-container class="md-block">
                <label for="password">Password</label>
                <input type="password" id="password" name="password" ng-model="formData.password" ng-minlength="8" required />

                <div ng-messages="projectForm.password.$error" ng-show="projectForm.password.$touched || projectForm.$submitted">
                    <div ng-message="required">required.</div>
                    <div ng-message="minlength">Passwords must be between 8 and 20 characters.</div>
                </div>
            </md-input-container>
            
            <md-input-container class="md-block">
                <label for="password_c">Confirm Password</label>
                <input type="password" id="password_c" name="password_c" ng-model="formData.password_c" valid-password-c required />
                <div ng-messages="projectForm.password_c.$error" ng-show="projectForm.password_c.$touched || projectForm.$submitted">
                    <div ng-message="required">Please confirm your password.</div>
                    <div ng-message="noMatch">Passwords do not match.</div>
                </div>
                <br /><br /><br />
                <pre>projectForm.password.$error = {{ projectForm.password.$error | json }}</pre>
                <pre>projectForm.password.$touched = {{ projectForm.password.$touched | json }}</pre>
                <br />
                <pre>projectForm.password_c.$error = {{ projectForm.password_c.$error | json }}</pre>
                <pre>projectForm.password_c.$touched = {{ projectForm.password_c.$touched | json }}</pre>
            </md-input-container>
        </form>
    </md-content>
</div>

Working Code Here: http://codepen.io/anon/pen/gPrMRM

Answer №1

The reason for this issue is due to a $parser not returning a value in your code. To resolve this, it is recommended to utilize the validators pipeline instead of the parsers within your directive.

<input type="password" id="confirm_password" name="confirm_password" required
       ng-model="userData.confirm_password"
       validate-password="{{userData.password}}" />


ctrl.$validators.comparePasswords = function (value) {

    // Check if both passwords are provided 
    if (!attrs.validatePassword || !value) {
        return true;
    }

    return value === attrs.validatePassword;
}

Make sure to include the original password as an attribute for validation purposes.

Answer №2

Don't forget to include the return statement in your $parser function:


ctrl.$parsers.unshift(function (viewValue, $scope) {
    var noMatch = viewValue !== scope.projectForm.password.$viewValue;
    scope.projectForm.password.$error = {};
    ctrl.$setValidity('noMatch', !noMatch);
    console.log("scope.projectForm.password.$error: ");
    console.dir(scope.projectForm.password.$error); 
    return viewValue;
})

If you need further assistance, check out this codepen

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

In my chat application, I encountered the error message "Received an expression instead of an assignment or function call - no-unused-expressions"

While working on my React Chat app and trying to access my Firebase, I encountered the error message: "Expected an assignment or function call and instead saw an expression no-unused-expressions" The error seems to be related to the assignment of this.rem ...

NodeJS constantly communicating with Rest API

Entering the world of Node.js is a new journey for me. I have a service with two endpoints available. The first endpoint is a post method that takes in a payload, processes it asynchronously, and immediately sends an acknowledgment to the caller. The secon ...

Animating SVG elements with the rotation property in SVG.js

Currently, I am utilizing Javascript, Jquery, SVG, and SVG.js in my project. My goal is to rotate a circle around its origin while it's animating. The issue arises when the animation keeps restarting abruptly, causing a jittery motion. Here is the ini ...

Navigating to new location following the final iteration in a loop of asynchronous updates in MongoDB

Currently, I am developing an application using Node/Express/Mongodb/Mongoskin. I am facing an issue with the code responsible for updating a collection of documents: db.collection('invoices').find().toArray(function(err, dbDocs) { if (err) t ...

Guide on Connecting an Angular Directive to a Kendo UI Model

After extensive research, I have yet to find a solution matching my specific problem online. Despite my efforts, I am struggling to pass the angular model/object through to the directive and bind it to the new element. It feels like I've hit a wall... ...

Encountering a 500 (Internal Server Error) when performing an $http post in C# MVC after including additional properties in the default User

I keep encountering a 500 Internal Server error while attempting to register a new user using ASP.net's default user authentication system. This functionality was previously working without any issues. However, after I tried to include a 'FirstN ...

Troubleshooting AngularJS bug

I've encountered a TypeError: Cannot read property 'get' of undefined while working on my login.controller.js code. I've tried several solutions but haven't been able to resolve it. Here is my code in the login.controller.js file: ...

Which one relies on the other: angular-data or angular-cache?

I'm struggling to get angular-cache set up properly. According to the documentation: Angular-cache is a dependency of angular-data and must be loaded before angular-data if you are using angular-data. That's all well and good, but what if I only ...

Performing a targeted ajax request to retrieve a set of data

Is it possible to create a collection using a specific ajax call instead of fetching by its URL? Normally, when fetching by a collection, the URL in the collection is used. However, I need to retrieve results from an ajax call rather than the URL. $.ajax( ...

Change a CSV string into a JSON array and assign it to a variable

I am working with JSON data that looks like this: [ { "Title": "PAGE A", "Users": "USRA" }, { "Title": "PAGE B", "Users": "USRA,USRB" } ] What is the most efficient method to convert the fields containing " ...

Open the .exe file using an HTML link in Firefox browser

While working on a project using php / js / html, I encountered the need to launch a C# application from my web page without requiring any downloads. The challenge was that I primarily use Mozilla Firefox and could only find solutions involving ActiveXOb ...

Tips for including a footer element in React:How can a footer division be

I need help with implementing a footer in my React web app. Currently, the body section in index.html looks like this: <body> <div id="root"></div> <script src="index.js"></script> </body> Inside index.js, the rend ...

Toggle between list elements using the inner text of the elements with jQuery

My issue lies in figuring out why my filter function isn't properly working for toggling li elements. JavaScript: $("#searchbox1").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#menulist li") ...

Prevent clicking on form until setInterval has been cleared using React useEffect

Here is a link to a sandbox replicating the behavior: sandbox demo I have integrated a hook in a React component to act as a countdown for answering a question. React.useEffect(() => { const timer = setInterval(() => { setTimeLeft((n ...

Implementing automatic line breaks in Bootstrap

When setting the "overflow scroll able" option, I want it to only allow scrolling in the y direction and if x content overflows, a line break should occur. I tried applying 'white-space', but it didn't work as expected. <ul class="s ...

Arranging items in Angular based on selection from the database

i have data in table: Id, word, score , score_list. score are 0.4, 0.2, -0.5, 0, -0.3 .... in score_list i have positive, negative , neutral. How can i sort data with select by score_list? This is html <select class="form-control"> <option> ...

A guide on how to implement promise return in redux actions for react native applications

I'm using redux to handle location data and I need to retrieve it when necessary. Once the location is saved to the state in redux, I want to return a promise because I require that data for my screen. Here are my actions, reducers, store setup, and ...

Modifying script variables using the Chrome console

There is a button on the website that looks like this: https://i.sstatic.net/G7PBF.png Clicking on this button triggers the following script: https://i.sstatic.net/rIdLW.png function count(){ let downloadTimer; var timeleft = 30; downloadTimer = setInte ...

Is it necessary to include a back button when navigating through paginated tables?

Within my AngularJS application, I have implemented pagination on the user list page. This allows me to retrieve ten users at a time from the server, with each click loading another set of ten users on a new page. The user details are presented in a tabl ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...