web-dev-qa-db-fra.com

Angular ng-messages: comment vérifier la confirmation du mot de passe?

LA SITUATION:

J'utilise la directive ng-messages pour une validation instantanée dans mon angular. Tout fonctionne bien sauf une chose: j'ai besoin de valider le champ 'confirmation du mot de passe' et je ne sais pas comment faire.

LE CODE:

<form name="autentication_form" novalidate="" ng-submit="submit_register()">

    <label class="item item-input">
        <span class="input-label">Email</span>
        <input type="text" name="email" ng-model="registerData.email" required>

        <div class="form-errors" ng-messages="autentication_form.email.$error" role="alert" ng-if='autentication_form.email.$dirty'>
            <div class="form-error" ng-message="required">You did not enter the email</div>
        </div>
    </label>

    <label class="item item-input">
        <span class="input-label">Password</span>
        <input type="password" name="password" ng-model="registerData.password" required>

        <div class="form-errors" ng-messages="autentication_form.password.$error" role="alert" ng-if='autentication_form.password.$dirty'>
            <div class="form-error" ng-message="required">Please enter the password</div>
        </div>
    </label>

    <label class="item item-input">
        <span class="input-label">Password confirmation</span>
        <input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required>

        <div class="form-errors" ng-messages="autentication_form.password_confirmation.$error" role="alert" ng-if='autentication_form.password_confirmation.$dirty'>
            <div class="form-error" ng-message="required">Password confirmation required</div>
        </div>
    </label>

</form>

LA QUESTION:

Comment puis-je vérifier que la confirmation de mot de passe correspond à l'aide de ng-messages?

27
FrancescoMussi

L'approche la plus simple consiste à utiliser un modèle. Fonctionne bien pour moi!

<input type="password" name="new_password1" ng-model="new_password1">

<input type="password" name="new_password2" ng-pattern="\b{{new_password1}}\b" ng-model="new_password2">
<div ng-messages="passwordForm.new_password2.$error">
    <div ng-message="pattern">Not equal!!!</div>
</div>
22
ebastuart

La meilleure approche consiste à utiliser une directive. Le problème majeur ici est que les entrées de mot de passe et de confirmation de mot de passe doivent être surveillées.

Voici la solution qui pourrait vous aider

angular.module('app', ['ngMessages'])

.controller('ctrl', function($scope) {
  $scope.registerData = {};
})


.directive('confirmPwd', function($interpolate, $parse) {
  return {
    require: 'ngModel',
    link: function(scope, elem, attr, ngModelCtrl) {

      var pwdToMatch = $parse(attr.confirmPwd);
      var pwdFn = $interpolate(attr.confirmPwd)(scope);

      scope.$watch(pwdFn, function(newVal) {
          ngModelCtrl.$setValidity('password', ngModelCtrl.$viewValue == newVal);
      })

      ngModelCtrl.$validators.password = function(modelValue, viewValue) {
        var value = modelValue || viewValue;
        return value == pwdToMatch(scope);
      };

    }
  }
});
<html ng-app="app">

<head>
  <script data-require="angular.js@~1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
  <script data-require="[email protected]" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-messages.js"></script>
  <script src="https://code.angularjs.org/1.3.15/angular.js"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="ctrl">
  <form name="autentication_form" novalidate="" ng-submit="submit_register()">
    <label class="item item-input">
      <span class="input-label">Email</span>
      <input type="text" name="email" ng-model="registerData.email" required="" />
      <div class="form-errors" ng-messages="autentication_form.email.$error" ng-if='autentication_form.email.$touched'>
        <span class="form-error" ng-message="required">You did not enter the email</span>
      </div>
    </label>
    <label class="item item-input">
      <span class="input-label">Password</span>
      <input type="password" name="password" ng-model="registerData.password" required />
      <div class="form-errors" ng-messages="autentication_form.password.$error" ng-if='autentication_form.password.$touched'>
        <span class="form-error" ng-message="required">Please enter the password</span>
      </div>
    </label>
    <label class="item item-input">
      <span class="input-label">Password confirmation</span>
      <input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required="" confirm-pwd="registerData.password" />
      <div class="form-errors" ng-messages="autentication_form.password_confirmation.$error" ng-if='autentication_form.password_confirmation.$touched'>
        <span class="form-error" ng-message="required">Password confirmation required</span>
        <span class="form-error" ng-message="password">Password different</span>
      </div>
    </label>
  </form>
</body>

</html>
9
AviG

Lors du développement, vous pouvez faire face au fait que vous devez créer vos propres chèques, ce qui affectera la validité du formulaire. Si ces vérifications sont simples, comme une comparaison des deux valeurs, il est préférable d'utiliser une ligne directrice générale, plutôt que d'écrire vos propres vérifications pour chaque situation. Regardez se-form-error directive.

Exemple en direct sur jsfiddle .

angular.module('ExampleApp', ['use', 'ngMessages'])
  .controller('ExampleController', function($scope) {

  });
.errors {
  color: maroon
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.min.js"></script>
<script src="https://cdn.rawgit.com/Stepan-Kasyanenko/use-form-error/master/src/use-form-error.js"></script>

<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">

    <form name="ExampleForm">
      <label>Password</label>
      <input ng-model="password" required />
      <br>
      <label>Confirm password</label>
      <input ng-model="confirmPassword" name="confirmPassword" use-form-error="isNotSame" use-error-expression="password && confirmPassword && password!=confirmPassword" required />
      <div ng-show="ExampleForm.$error.isNotSame" class="errors">Passwords Do Not Match!</div>
      <div ng-messages="ExampleForm.confirmPassword.$error" class="errors">
        <div ng-message="isNotSame">
          Passwords Do Not Match (from ng-message)!
        </div>
      </div>
    </form>

  </div>
</div>
4
Stepan Kasyanenko

Voici ce que j'ai fait (en utilisant ng-pattern):

<md-input-container class="md-block">
  <label>New Password</label>
  <input ng-model="user.password" name="password" type="password" required ng-pattern="'.{8,}'" />
  <div ng-messages="form.password.$error">
    <div ng-message="required">Password required.</div>
    <div ng-message="pattern">Password must be at least 8 characters.</div>
  </div>
</md-input-container>
<md-input-container class="md-block">
  <label>Confirm Password</label>
  <input ng-model="user.confirmPassword" name="confirmPassword" type="password" ng-pattern="user.password|escapeRegex" required />
  <div ng-messages="form.confirmPassword.$error">
    <div ng-message="required">Password confirmation required.</div>
    <div ng-message="pattern">Passwords do not match.</div>
  </div>
</md-input-container>

Et le filtre suivant convertit le ng-pattern regex à un littéral:

module.filter('escapeRegex', function(){
  return function(str){
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  }
});
1
Trevor

ngMessage fonctionne en ajoutant $ error. message_field_name au nom du champ DOM dans l'objet formulaire (dans le cadre du cours). Donc, si le nom de votre formulaire DOM est autentication_form et le nom du champ DOM est password_confirmation, vous devez définir $ scope.autentication_form.password_confirmation. $ Error. nomatch (ou le nom de ngMessage que vous voulez) sur true pour afficher l'erreur "ne correspond pas".

Balisage:

<input type="password" name="password_confirmation" ng-model="registerData.password_confirmation" required />

<div ng-messages="autentication_form.password_confirmation.$error">
                <div ng-message="required">Please repeat your password.</div>
                <div ng-message="nomatch">Doesn't match.</div>
            </div>
</div>

Code, rien de spécial, juste regarder les deux mots de passe:

$scope.$watch("registerData.password + registerData.password_confirmation", function () {
            $scope.autentication_form.password_confirmation.$error.nomatch = $scope.registerData.password !== $scope.registerData.password_confirmation;
        });
1
Oleg