nevergiveup nevergiveup - 6 months ago 29
AngularJS Question

Angularjs : display message

i'm try to display message when password don't match but not not showing any idea ?i'm try to display message when password don't match but not not showing any idea ?

directive:

angular.module('crud')
.directive('equal', function () {
return {
require: 'ngModel',
scope: {
equal: '='
},
link: function(scope, elem, attrs, ctrl) {

ctrl.$validators.equal = function(modelValue, viewValue) {
return modelValue === scope.equal;
};

scope.$watch('equal', function(newVal, oldVal) {
ctrl.$validate();
});
}
};
});


html

<form name="userForm" ng-submit="signup()" class="form-horizontal" role="form" >
<input type="password" class="form-control ng-invalid submitted" id="password" name="password" ng-model="password" ng-minlength="8" ng-maxlength="20" required />

<input type="password" equal="password" class="form-control ng-invalid submitted" id="confirmPassword" name="confirmPassword" ng-model="confirmPassword" required />

<span ng-show="userForm.password.$error.equal && userForm.password.$dirty">Passwords don't match.</span>
</form>

Answer

Everything is fine with one exception, you should add equal directive on password input, because you are displaying errors for password, so you should validate password. Other than that it is ok. Although you might consider using ng-messages for displaying errors.

angular.module('crud', ['ngMessages']);

angular.module('crud')
  .directive('equal', function () {
    return {
      require: 'ngModel',
      scope: {
        equal: '='
      },
      link: function(scope, elem, attrs, ctrl) {
        ctrl.$validators.equal = function(modelValue, viewValue) {
          return modelValue === scope.equal;
        };

        scope.$watch('equal', function(newVal, oldVal) {
          ctrl.$validate();
        });
      }
    };
  });
.valid {
  border: 1px solid green;
}

.invalid {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<script src="https://code.angularjs.org/1.5.5/angular-messages.js"></script>
<div ng-app="crud">
<form name="userForm"  class="form-horizontal" role="form" >
    <input type="password" class="form-control ng-invalid submitted" id="password" name="password" equal="confirmPassword" ng-model="password" ng-minlength="8" ng-maxlength="20" ng-class="{'valid':  userForm.password.$valid || !userForm.password.$dirty, 'invalid': userForm.password.$invalid && userForm.password.$dirty}"  required />

     <input type="password"  class="form-control submitted" id="confirmPassword" name="confirmPassword" ng-model="confirmPassword" required  />

    <div ng-messages="userForm.password.$error" ng-show="userForm.password.$dirty" role="alert">
      <div ng-message="required">Please enter a value for this field.</div>
      <div ng-message="equal">Passwords don't match.</div>
    </div>
  
</form>
</div>