Checking password fields in Angular upon submission or when they have been edited

i created a controller and form with validation rules, but i'm struggling to ensure that the confirm_password matches the password?

html

<div class="col-md-5" ng-controller="RegisterController as vm">
    <form id="sign_up" name="SignUp" ng-submit="vm.register(SignUp)" novalidate>
        <div class="box_form">
            <div class="form-group">
                <label>Email</label>
                <input type="email" class="form-control" name="email" ng-model="vm.email" placeholder="Your email" required>
                <p ng-show="(SignUp.email.$error.email || SignUp.email.$error.required) && (SignUp.terms.$dirty || vm.submitted)" class="help-block ng-binding"
                    style="">Email is invalid.</p>
            </div>
            <div class="form-group">
                <label>Username</label>
                <input type="text" class="form-control" name="username" ng-model="vm.username" ng-minlength="3" ng-maxlength="14" placeholder="Your username"
                    required>
                <p ng-show="SignUp.username.$error. && (SignUp.username.$dirty || vm.submitted)" class="help-block ng-binding" style="">Username is invalid.</p>
            </div>
            <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"
                    required>
                <p ng-show="SignUp.password.$error && (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>
                <p ng-show="(SignUp.confirm_password.$dirty || vm.submitted)" class="help-block ng-binding">Passwords do not match.</p>
            </div>
            <div class="checkbox-holder text-left">
                <div class="checkbox_2">
                    <input type="checkbox" value="accept" id="check_2" name="terms" ng-model="terms" required>
                    <label for="check_2">
                        <span>I Agree to the
                            <strong>Terms &amp; Conditions</strong>
                        </span>
                    </label>
                </div>
            </div>
            <!-- validation -->
            <p class="alert alert-danger text-center" ng-show="SignUp.terms.$error.required && (SignUp.terms.$dirty || vm.submitted)">Please accept terms and conditions.</p>

            <div class="form-group text-center add_top_30">
                <button class="btn_1" id="sign_up_btn" type="submit">Sign Up</button>
            </div>
        </div>

    </form>
</div>

controller

(function () {
  'use strict';

  angular
    .module('KryptoApp')
    .controller('RegisterController', RegisterController);
  RegisterController.$inject = ['$location', '$scope', 'Authentication'];

  function RegisterController($location, $scope, Authentication) {
    var vm = this;

    vm.register = register;

    function register(form) {
      vm.submitted = true;
      if(form.$valid) {
        Authentication.register(vm.email, vm.password, vm.confirm_password, vm.username);
      }
    }


  }

})();

Answer №1

One potential solution could be to develop a custom directive specifically for this scenario:

var validateMatchingFields = function() {
return {
    require: "ngModel",
    scope: {
        otherModelValue: "=validateMatchingFields"
    },
    link: function(scope, element, attributes, ngModel) {

        ngModel.$validators.validateMatchingFields = function(modelValue) {
            return modelValue == scope.otherModelValue;
        };

        scope.$watch("otherModelValue", function() {
            ngModel.$validate();
        });
    }
};};

Then, you can register the directive in your module like so:

module.directive("validateMatchingFields", validateMatchingFields);

Finally, in your HTML template:

<input type="password" name="confirmPassword" 
    ng-model="registration.user.confirmPassword"
    required 
    validate-matching-fields="registration.user.password" />

<div ng-messages="registrationForm.confirmPassword.$error"
  ng-messages-include="messages.html"></div>

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

What is the mechanism behind the functioning of StackOverflow's notification system?

Could you explain the technique that is utilized to transmit and receive data from the client to the server? How does it manage to provide almost real-time results when new changes take place? Can anyone demonstrate the code being used for this process? ...

Transitions in Vue do not function properly when used in conjunction with a router-view containing a

Recently, I developed a component where I implemented router-view exclusively to facilitate route-based changes. It's worth mentioning that this is the second instance of router-view, with the first one residing in the App.vue component. Interestingly ...

The final child element is null when using lastElementChild

For my current Javascript project, I am tackling the task of dividing the page into two separate div elements. The left div is populated with randomly positioned images, and then I utilized the .cloneNode() method to duplicate this on the right side, exclu ...

Localization of text in jQuery timeago.js

I have implemented J Query time ago to display date and time on my website. I am currently working on a multilanguage website where I want the time ago message to show as "1 min ago" for English users and "1 دقیقه قبل" for Farsi users. Can I achi ...

Embed three.js within a div container in an HTML document

I've been attempting to place the Canvas Lines three.js inside another div, but it doesn't seem to be working as expected. Instead, when I try, the JS code places the canvas at the very end of the body. Can anyone tell me why this is happening? ...

Can anyone advise me on connecting a custom filter to an HTML template for input types?

Imagine this scenario: <input type="text" name="classDuration" data-ng-model="ClassDuration" /> Now, let's say I have a custom filter called formatDuromation defined in my JavaScript file for customers. This filter converts numbers to the form ...

The status is currently not defined when attempting to retrieve JSON data and display it on individual pages for each piece of data

I have written some code where I am trying to display the attributes of a selected product from my product page based on its ID. For example, when a product is clicked, it should redirect to a URL like /#/product/2 and display all the attributes of the pro ...

What is the impact of a floated element on vertical spacing?

I have come across an article discussing the usage of CSS, but I am puzzled as to why image number four is not positioned below image number one. Instead, it appears below image number three. Can someone please explain this to me? Here is the HTML code sni ...

Vue.js HTML not refreshing after axios request changes object property

Issue with Vue.js not updating HTML after axios GET request. Here's the structure: <span @click="tryResponse"> Data_object: {{ data_object }} <br> Data_object.serial: {{ data_object.serial }} <br> </span> Data ...

Exploring the context of file upload events and analyzing javascript functionality

Can you help me conditionally trigger the file upload dialog using JavaScript based on an Ajax response? <input type="file" id="Upload"> I have hidden the input element as I don't want to display the default file upload button. Instead, ther ...

JavaScript Object DeclarationCreating Objects in JavaScript

In this scenario, I have the following code snippet. Upon calling the constructor, an object is created. When updating the fields, modifications are made as shown below. It's important to note that direct modification of the Comment() function is not ...

"Obtaining mouse coordinates in VueJS: A step-by-step guide

I am using a component that is activated by v-on:click="someMethod". Is there a way to retrieve the X and Y coordinates of the mouse click within this component? Extra context: The component I'm working with is an HTML5 Canvas element. ...

Utilize Google Home to browse through nearby websites and respond to inquiries by incorporating Javascript

Can Google Home be programmed to read from a local webpage and provide answers based on the content of that page through Javascript? ...

The $POST method is failing to update the information

I've encountered an issue with my script that I can't seem to figure out. After numerous tests, it seems like the main problem lies within the Ajax request. Interestingly, I have used the Ajax request successfully in a previous version of my scri ...

Creating a Three.js 3D Text Effect with Layers of Letters

Why are my 3D text letters overlapping in the threejs TextGeometry when viewed from an angle? https://i.sstatic.net/W0ocu.png See the code snippet below: class MyScene { // Code for handling Three.js scene and elements constructor(elementSelector ...

Is it not odd that there are two '=>' symbols in an arrow function when there is typically only one? What could this possibly signify?

function updateStateValue(name) { return (event) => { setState({ ...state, [name]: event.target.checked }); }; } To view the full code example, visit CodeSandbox. ...

PostMan gives me an error when I attempt to send an image file to NodeJS using multer (req.file is undefined)

After encountering issues with saving image files to the server using multer-s3, I attempted to use multer and s3Client instead. Unfortunately, I faced similar challenges as req.file or req.files from the multer-s3 middleware continued to return undefined. ...

Use an if-else statement in jQuery with selectors to determine if a specific div element has been added to it

What if you have a main div and append one of these sub-divs to it? For example: <div class ="append"> <div id ="one"></div> <div id ="two"></div> </div> Then in jQuery, could you do something like this: if ($(.a ...

Utilize the v-if directive within a v-for loop

I am currently iterating over an array named cars using the v-for directive. I would like to implement a condition within this loop so that if the color property matches a certain value, a specific CSS style is applied. <p v-for="car in cars" ...

The presence of 'touched' within Angular validation is causing a delay in method execution

Upon utilizing this validation method, it became apparent: <label>Password</label> <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': f.password.touc ...