modify the ng-invalid class when making changes to double entry fields

I am facing an issue with a password and password confirmation field that are linked using a directive. Additionally, I have CSS that sets the border color when ng-invalid. The problem arises when I enter the password in the confirm_password first and then the same password in the password, it does not remove the 'ng-invalid' class. Is there a way to instruct Angular to update the classes of other fields when editing the password?

HTML

<div class="form-group">
    <label>Password</label>
    <input type="password" class="form-control" name="password"
           ng-model="vm.password" ng-minlength="6" ng-maxlength="24" 
           placeholder="Your password"
           equals="vm.confirm_password" required>
    <p ng-show="SignUp.password.$invalid 
                && (SignUp.password.$dirty || vm.submitted)" 
       class="help-block ng-binding" style="">Password is invalid.</p>
</div>
<div class="form-group">
    <label>Confirm Password</label>
    <input type="password" class="form-control" name="confirm_password"
           ng-model="vm.confirm_password"
           ng-minlength="6" ng-maxlength="24"
           ng-model="vm.confirm_password"
           placeholder="Confirm your password"
           required nx-equal="vm.password">
    <p ng-show="SignUp.confirm_password.$error.nxEqual
                && (SignUp.confirm_password.$dirty || vm.submitted)" 
       class="help-block ng-binding">Passwords do not match.</p>
</div>

CSS

input.ng-dirty.ng-invalid {
    border-color: #a94442;
}

.ng-submitted input.ng-invalid {
    border-color: #a94442;
}

Directive Function

function ComparePassword() {
return {
  require: 'ngModel',
  link: function (scope, elem, attrs, model) {
    if (!attrs.nxEqual) {
      console.error('nxEqual expects a model as an argument!');
      return;
    }
    scope.$watch(attrs.nxEqual, function (value) {
      model.$setValidity('nxEqual', value === model.$viewValue);
    });
    model.$parsers.push(function (value) {
      var isValid = value === scope.$eval(attrs.nxEqual);
      model.$setValidity('nxEqual', isValid);
      return isValid ? value : undefined;
    });
  }
}
}

Answer №1

Implement the compare directive to monitor the other field:

app.directve("compareTo", compareTo);

function compareTo() {
  return {
      require: "ngModel",
      link: function(scope, elem, attrs, ngModel) {

        ngModel.$validators.compareTo = function(modelValue) {
          return modelValue == scope.$eval(attrs.compareTo);
        };

        scope.$watch(attrs.compareTo, function() {
          ngModel.$validate();
        });
      }
  };
}

How to use:

<form name="form1">
    <input type="password" name="password" required
           ng-model="user.password" />          
    <input type="password" name="confirmPassword" required 
           ng-model="user.confirmPassword" compare-to="user.password" />    
</form>

<div ng-show="form1.comfirmPassword.$error.compareTo">
   Error: Password entries must match
</div>

Considerations on double entry verification

Double entry verification:

  • Increases user workload;
  • Can be circumvented by copy-pasting or autofill tools;
  • Makes sure fields match, not content validity;
  • May appear patronizing to users;

Exploring alternatives like authentication or easy reset options is worth exploring.

— Formulate Information Design Blog - Double entry of form fields

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

Automated mocking of controller and service dependencies in Angular

When working with Angular unit testing, manually mocking and stubbing all dependencies can be quite cumbersome, especially when only generic mocks are needed. Additionally, whenever the dependency list for a service/controller changes, tests may break due ...

I need to mass upload a collection of resumes stored in a zip file, then extract and display the content of each resume using a combination of HTML

I recently used a service to extract and retrieve the contents of a zip file. I am trying to read the content of the files and integrate them into the scope of my Angular project. Any suggestions would be greatly appreciated. Below is an outline of my func ...

What is the method for achieving a seamless rosace effect in CSS?

While working on my website, I added an interesting effect to a circle. Currently, the circle opens automatically when hovering the mouse over it and closes when the mouse moves away. However, I would like to modify it so that it automatically opens and cl ...

Is it feasible to conceal a certain field once the user has chosen another field?

Looking to create an IF statement that will help me establish a specific rule. On a customer portal page, customers can open tickets via a form where they provide information such as "software product" and "environment" from dropdown lists, as well as othe ...

Error message: angularjs $routeProvider - the requested route was not found

I have encountered an issue with routing in my AngularJS application that is using RequireJS. The problem is that when I try to route to a specific path, it always defaults back to the root path "/". Interestingly, changing the path from /post to /:post ...

Guide on how to eliminate the click effect from a Bootstrap 4 button

I have been struggling with the issue of removing the box-shadow effect from Bootstrap 4 buttons. I searched for solutions on various forums but couldn't find one that worked for me. So, I decided to try some custom CSS code I found online. I was able ...

Learn how to dynamically apply a CSS attribute for a set period of time using jQuery and automatically revert it back to its original state after 2 seconds

Is there a way to apply a CSS attribute to a specific element (like a div) for only 2 seconds? Here is what I have tried so far: HTML: <div class="custom-div">bar</div> <input class="button" type="button" value="press me" /> JQuery: $ ...

Exploring the issue of varying site header widths in WordPress: The mystery behind my unfinished author page

Why is there a difference in site header width between the author page and other pages? It seems incomplete on the author page while it's complete on other pages. What am I missing? <header id="site-header" role="banner&q ...

Using Passport.js with client-side templating: A step-by-step guide

I've been using passport js for authentication, but I'm also implementing the angular $route service for client-side templating. This dual approach has left me uncertain about how to effectively utilize passport, especially since most of the exam ...

In this guide, learn the best way to dynamically adjust image height to match the height of any device

I am trying to make sure that the image on the front page of my website fits the height of the screen or device, and resizes responsively without cropping when the device height changes. How can I achieve this? If you need a visual example of what I mean, ...

Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser: I attempted to store the data in a variable with the following code: $http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode& ...

Create a hover effect on HTML map area using CSS

Is it possible to change the background color of an image map area on hover and click without using any third-party plugins? I attempted the following code: $(document).on('click', '.states', function(){ $(this).css("backgro ...

Ways to make a background stretch infinitely in the x-axis

Currently, my header has a grey background with a width of 100% and a maximum width of 1000px. To extend the grey background beyond the 1000px limit, I have a separate div with an absolute position behind the header div. The issue arises when the user scro ...

Utilizing a dynamic value in an Angular directive

For my latest project, I am working on developing a basic JSON pretty-printer directive using angular.js. Here is the code snippet I have so far: (function(_name) { function prettyJson() { return { restrict: 'E', ...

Adjust the CSS styling to ensure that the div or iframe expands to fit the entire height of the

Having trouble making a map embedded via an iframe on a WordPress page display responsively at full height independent of the device? Check out: . To clarify, by full height, I mean that the bottom of the map should not extend beyond the screen, eliminati ...

Testing the Compatibility of Angular JS and Angular 8 in a Hybrid Application

I am currently working on a hybrid application using AngularJS and Angular 8. The new components I create in Angular need to be downgraded for use in AngularJS. Here is a snippet of the module code: @NgModule({ // Declarations and Imports providers ...

How can I ensure that the size of the Dropdown Menu Item matches its parent in both Bootstrap and CSS styles?

I am working on a navigation bar that has a dropdown menu which appears on hover. I want the size of the dropdown menu items to match the size of the parent element. Here is an image for reference: https://i.stack.imgur.com/oNGmZ.png Currently, the "One ...

Zero results returned for the angularjs script

I am working on enhancing my skills in angularjs, but I am facing an issue where only the categories are being displayed and the products are not showing up. There are no error messages, so I am having trouble pinpointing where the problem lies. Here is t ...

Implementing pagination with Django-REST and AngularJS

I successfully integrated my angularjs app with django-rest, but encountered a problem when implementing pagination. Below is the code for my restservice and controller: // restservices.js // API call for all images in an event services.factory('Imag ...

What is the best way to differentiate the behavior of two identical classes using a single JavaScript function?

Can someone help me figure out how to make two circles move differently with the same JavaScript function? I'm new to JavaScript and struggling to differentiate between classes in HTML to achieve this. My goal is to have each circle move randomly and ...