Angular 2 4 5 6 7 8

Password and Confirm Password validation in AngularJs Example

The following example will work to verify the confirm password using compareTo directive.

Example: HTML Code -
    <form class="form-horizontal" role="form" name="CreateEmployeeForm" novalidate>
        <div class="col-sm-6 col-sm-offset-3">
            <div class="row">               
                <div class="form-group">
                    <div class="col-sm-12">
                        <span class="smoothy">Password</span>
                        <input type="password" class="form-control placeholder" name="Password" ng-model="Employee.Password" ng-required="true" placeholder="Password">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-12">
                        <span class="smoothy">Confirm Password</span>
                        <input type="password" class="form-control placeholder" name="ConfirmPassword" ng-model="Employee.ConfirmPassword" ng-required="true" compare-to="Employee.Password" placeholder="Confirm Password">
                        <div ng-messages="CreateEmployeeForm.ConfirmPassword.$error" ng-if="CreateEmployeeForm.ConfirmPassword.$touched">
                            <span ng-message="compareTo">Password not matched.</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

AngularJs directive Code –
var compareTo = function () {
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function (scope, element, attributes, ngModel) {
            ngModel.$validators.compareTo = function (modelValue) {
                return modelValue == scope.otherModelValue;
            };

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

app.directive("compareTo", compareTo);

AngularJs Controller Code –
var app = angular.module("app", []);
app.controller("confirmCtrl", function ($scope) {
    $scope.Employee = {
        password: "",
        confirmPassword: ""
    };
});
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^