chỉ thị kiểm tra mật khẩu trong anglejs


76

Tôi đang viết chỉ thị xác minh mật khẩu:

 Directives.directive("passwordVerify",function(){
    return {
        require:"ngModel",
        link: function(scope,element,attrs,ctrl){
            ctrl.$parsers.unshift(function(viewValue){
                var origin = scope.$eval(attrs["passwordVerify"]);
                if(origin!==viewValue){
                    ctrl.$setValidity("passwordVerify",false);
                    return undefined;
                }else{
                    ctrl.$setValidity("passwordVerify",true);
                    return viewValue;
                }
            });

        }
    };
});

html:

<input data-ng-model='user.password' type="password" name='password' placeholder='password' required>
<input data-ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password">

Cho 2 trường mật khẩu trong một biểu mẫu, nếu cả hai giá trị mật khẩu bằng nhau thì trường bị ảnh hưởng bởi lệnh là hợp lệ. Vấn đề là nó hoạt động theo một chiều (tức là khi tôi nhập mật khẩu vào trường xác minh mật khẩu). Tuy nhiên, khi trường mật khẩu ban đầu được cập nhật, xác minh mật khẩu không hợp lệ.

Bất kỳ ý tưởng nào về cách tôi có thể có "xác minh ràng buộc hai chiều?"

Câu trả lời:


60

Điều này sẽ giải quyết nó:

Lượt xem:

<div ng-controller='Ctrl'>
   <form name='form'>
      <input data-ng-model='user.password' type="password" name='password' placeholder='password' required>
      <div ng-show="form.password.$error.required">
        Field required</div>
      <input ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password">
      <div ng-show="form.confirm_password.$error.required">
        Field required!</div>
      <div ng-show="form.confirm_password.$error.passwordVerify">
        Fields are not equal!</div>
   </form
</div>

Chỉ thị

var app = angular.module('myApp', []);

app.directive("passwordVerify", function() {
   return {
      require: "ngModel",
      scope: {
        passwordVerify: '='
      },
      link: function(scope, element, attrs, ctrl) {
        scope.$watch(function() {
            var combined;

            if (scope.passwordVerify || ctrl.$viewValue) {
               combined = scope.passwordVerify + '_' + ctrl.$viewValue; 
            }                    
            return combined;
        }, function(value) {
            if (value) {
                ctrl.$parsers.unshift(function(viewValue) {
                    var origin = scope.passwordVerify;
                    if (origin !== viewValue) {
                        ctrl.$setValidity("passwordVerify", false);
                        return undefined;
                    } else {
                        ctrl.$setValidity("passwordVerify", true);
                        return viewValue;
                    }
                });
            }
        });
     }
   };
});

1
Tôi đã sử dụng đoạn mã xác thực trong tài liệu, hãy để tôi thử mã của bạn.
mpm 23/12/12

Tôi đã thay đổi câu trả lời của mình. Điều này sẽ hoạt động. Xem jsFiddle
asgoth 23/12/12

Điều này vẫn không cung cấp ràng buộc 2 chiều, hoặc một cái gì đó đã thay đổi kể từ đó?
Hadesara

1
Tôi đồng ý với CWSpear. Giải pháp nên được sửa chữa với lỗi đã nhận xét ở trên
gyss 27/09/2016

9
Có một rò rỉ bộ nhớ với giải pháp này. Mọi sự kiện xem được kích hoạt bằng cách đẩy một trình phân tích cú pháp khác vào mảng ctrl. $ Parsers. Kiểm tra ctrl. $ Parsers.length ở cuối trình xử lý sự kiện đồng hồ sẽ hiển thị điều này.
mshiltonj

114

Tôi sử dụng lệnh sau vì tôi muốn xác thực lại cả hai trường đầu vào bất kể giá trị 1 hay giá trị 2 đã được thay đổi:

chỉ thị:

'use strict';

angular.module('myApp').directive('equals', function() {
  return {
    restrict: 'A', // only activate on element attribute
    require: '?ngModel', // get a hold of NgModelController
    link: function(scope, elem, attrs, ngModel) {
      if(!ngModel) return; // do nothing if no ng-model

      // watch own value and re-validate on change
      scope.$watch(attrs.ngModel, function() {
        validate();
      });

      // observe the other value and re-validate on change
      attrs.$observe('equals', function (val) {
        validate();
      });

      var validate = function() {
        // values
        var val1 = ngModel.$viewValue;
        var val2 = attrs.equals;

        // set validity
        ngModel.$setValidity('equals', ! val1 || ! val2 || val1 === val2);
      };
    }
  }
});

sử dụng

<input type="password" ng-model="value1" equals="{{value2}}" required>
<input type="password" ng-model="value2" equals="{{value1}}" required>

4
Tôi thấy điều này hoạt động khá tốt. Một điều khiến tôi mất cảnh giác là nếu bạn có một số trình xác thực góc cạnh khác như: ng-minlengthtrên trường đầu tiên, thì mô hình đó không được đặt cho đến khi nó thực sự hợp lệ
Intellix

5
Tôi được bao bọc ngModel.$setValidityvới if (val1 && val2) { .. }chỉ nên hình thức không phải là không hợp lệ khi cả hai giá trị là rỗng.
jesal

4
Điều này có một số vấn đề nhỏ khi có nhiều quy tắc xác thực hơn trong trò chơi. Nếu xác nhận khác thất bại, góc không cập nhật các mô hình và các công cụ kỳ lạ xảy ra trong sự so sánh ...
user2173353

7
Nó hiệu quả tuyệt vời đối với tôi. Là một người mới, nó sẽ hữu ích để thêm chuỗi xác thực vào điều này. [form name].[field name].$error.equalsSử dụng điều này để kiểm soát những trường nên hoặc sẽ hiển thị. Tôi đang sử dụng nó cho các nhãn lỗi.
metric152

3
Tôi nghĩ rằng nó tốt hơn để thay thế ngModel.$setValidity('equals', val1 === val2);vớingModel.$setValidity('equals', ! val1 || ! val2 || val1 === val2);
bullgare

85

Tạo một chỉ thị riêng cho việc này là không cần thiết. Đã có một bản xây dựng trong công cụ xác thực mật khẩu Angular UI . Với điều này, bạn có thể làm:

<input name="password" required ng-model="password">
<input name="confirm_password"
       ui-validate=" '$value==password' "
       ui-validate-watch=" 'password' ">

 Passwords match? {{!!form.confirm_password.$error.validator}}

3
hiện yêu cầu jQuery
Intellix

24
@DominicWatson Bạn đang phản đối tôi vì điều gì? Câu hỏi này là về góc cạnh và tôi đề cập đến các tài liệu về góc cạnh. Hãy tìm hiểu nó nếu bạn không hiểu sự khác biệt giữa chúng.
xe đạp

24
@DominicWatson Chỉ thị ở đây github.com/angular-ui/ui-utils/blob/master/modules/validate/… ngoại trừ từ jquery lite, không có jquery kỳ quái nào trong đó. Nếu bạn không thích jquery, bạn không nên sử dụng framework này vì nó kết hợp jquery.
xe đạp

3
Tôi đang gặp vấn đề tương tự như bài viết gốc. Nếu có thứ gì đó đã được tích hợp sẵn cho góc-ui, liệu bạn có thể sử dụng nó thay vì phát minh lại bánh xe?
PeterG

2
@PeterG Tôi không nghĩ Dominic Watson có manh mối về những gì anh ấy đang nói
xe đạp

22

Tuy nhiên, một công việc khác của điều này là khớp mô hình của một đầu vào với giá trị của đầu vào khác.

app.directive('nxEqual', function() {
    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;
            });
        }
    };
});

Vì vậy, nếu mô hình của hộp mật khẩu là login.passwordthì bạn đặt thuộc tính sau trên hộp xác minh: nx-equal="login.password"và kiểm tra cho formName.elemName.$error.nxEqual. Như vậy:

<form name="form">
    <input type="password" ng-model="login.password">
    <input type="password" ng-model="login.verify" nx-equal="login.password" name="verify">
    <span ng-show="form.verify.$error.nxEqual">Must be equal!</span>
</form>

Phiên bản mở rộng:

Đối với một dự án mới của tôi, tôi phải sửa đổi chỉ thị trên để nó chỉ hiển thị nxEquallỗi khi và chỉ khi, đầu vào xác minh có giá trị. Nếu không, nxEquallỗi sẽ được tắt tiếng. Đây là phiên bản mở rộng:

app.directive('nxEqualEx', function() {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, model) {
            if (!attrs.nxEqualEx) {
                console.error('nxEqualEx expects a model as an argument!');
                return;
            }
            scope.$watch(attrs.nxEqualEx, function (value) {
                // Only compare values if the second ctrl has a value.
                if (model.$viewValue !== undefined && model.$viewValue !== '') {
                    model.$setValidity('nxEqualEx', value === model.$viewValue);
                }
            });
            model.$parsers.push(function (value) {
                // Mute the nxEqual error if the second ctrl is empty.
                if (value === undefined || value === '') {
                    model.$setValidity('nxEqualEx', true);
                    return value;
                }
                var isValid = value === scope.$eval(attrs.nxEqualEx);
                model.$setValidity('nxEqualEx', isValid);
                return isValid ? value : undefined;
            });
        }
    };
});

Và bạn sẽ sử dụng nó như vậy:

<form name="form">
    <input type="password" ng-model="login.password">
    <input type="password" ng-model="login.verify" nx-equal-ex="login.password" name="verify">
    <span ng-show="form.verify.$error.nxEqualEx">Must be equal!</span>
</form>

Hãy thử nó: http://jsfiddle.net/gUSZS/


3
Cái này là tốt nhất. Nó ngắn gọn nhất. Nó hoạt động trên các giá trị mô hình và nó hoạt động theo cả hai cách.
CMCDragonkai

Tuy nhiên, có một điều là đường ống phân tích cú pháp $ phải trả về giá trị hoặc không xác định. Bằng cách đó, các đường ống tiếp theo không chỉ kết thúc bởi vì nó luôn được trả về không xác định khi không có hàm trả về. Ngoài ra phạm vi nên sai.
CMCDragonkai

@CMCDragonkai: Bắt tốt! Tôi đã cập nhật giá trị trả về của hàm phân tích cú pháp. Về phạm vi, theo như tôi biết thì nó mặc định false, vì vậy không chỉ định rõ ràng phạm vi, nó bằng scope: false.
Fredric

Tôi nghĩ rằng nó thực sự được mặc định là true là phạm vi con. Nhưng tôi đã không kiểm tra gần đây.
CMCDragonkai

1
@GillBates Sử dụng một phạm vi cô lập và ràng buộc đối số bằng =sẽ không kiểm tra lại đầu vào đầu tiên sau khi nó đã được điền vào. Tôi đã thực hiện một JSFiddle nhanh chóng hiển thị sự cố này.
Fredric

14

Tôi đã làm điều đó mà không cần chỉ thị.

<input type="password" ng-model="user.password" name="uPassword" required placeholder='Password' ng-minlength="3" ng-maxlength="15" title="3 to 15 characters" />
    <span class="error" ng-show="form.uPassword.$dirty && form.uPassword.$error.minlength">Too short</span>
    <span ng-show="form.uPassword.$dirty && form.uPassword.$error.required">Password required.</span><br />

    <input type="password" ng-model="user.confirmpassword" name="ucPassword" required placeholder='Confirm Password' ng-minlength="3" ng-maxlength="15" title="3 to 15 characters" />
    <span class="error" ng-show="form.ucPassword.$dirty && form.ucPassword.$error.minlength">Too short</span>
    <span ng-show="form.ucPassword.$dirty && form.ucPassword.$error.required">Retype password.</span>
    <div ng-show="(form.uPassword.$dirty && form.ucPassword.$dirty) && (user.password != user.confirmpassword)">
        <span>Password mismatched</span>
    </div>

4
Bạn nên sử dụng một chỉ thị như đã được chỉ ra, biểu mẫu vẫn ở trạng thái hợp lệ. Nếu không, bạn cũng có thể tạo một số trình nghe jquery cho nó.
xe đạp


8

Kể từ phiên bản 1.3.0-beta12, đầu vào không hợp lệ không ghi vào ngModel, vì vậy bạn không thể xem VÀ SAU đó xác thực như bạn có thể thấy ở đây: http://plnkr.co/edit/W6AFHF308nyKVMQ9vomw?p=preview . Một đường dẫn trình xác thực mới đã được giới thiệu và bạn có thể đính kèm vào đó để đạt được điều tương tự.

Trên thực tế, trên ghi chú đó, tôi đã tạo một thành phần bower cho các trình xác thực bổ sung phổ biến: https://github.com/intellix/angular-validators bao gồm điều này.

angular.module('validators').directive('equals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('equals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.equals = function(value) {
                return value === attrs.equals;
            };
        }
    };
});

angular.module('validators').directive('notEquals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('notEquals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.notEquals = function(value) {
                return value === attrs.notEquals;
            };
        }
    };
});

giải pháp tốt nhất cho đến nay tôi đoán
Rathma

7

Tôi đã sử dụng chỉ thị này thành công trước đây:

 .directive('sameAs', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (viewValue === scope[attrs.sameAs]) {
          ctrl.$setValidity('sameAs', true);
          return viewValue;
        } else {
          ctrl.$setValidity('sameAs', false);
          return undefined;
        }
      });
    }
  };
});

Sử dụng

     <input ... name="password" />
    <input type="password" placeholder="Confirm Password" 
name="password2" ng-model="password2" ng-minlength="9" same-as='password' required>

Tôi như giải pháp này là tốt nhất - không hạn chế nó để phù hợp với mật khẩu
Shaz

7

Tôi đang giải quyết vấn đề tương tự và tìm thấy một bài đăng blog hay về nó do Piotr Buda viết. Đây là một bài đọc hay và nó giải thích quá trình này rất tốt. Mã như sau:

directives.directive("repeatPassword", function() {
    return {
        require: "ngModel",
        link: function(scope, elem, attrs, ctrl) {
            var otherInput = elem.inheritedData("$formController")[attrs.repeatPassword];

            ctrl.$parsers.push(function(value) {
                if(value === otherInput.$viewValue) {
                    ctrl.$setValidity("repeat", true);
                    return value;
                }
                ctrl.$setValidity("repeat", false);
            });

            otherInput.$parsers.push(function(value) {
                ctrl.$setValidity("repeat", value === ctrl.$viewValue);
                return value;
            });
        }
    };
});

Vì vậy, bạn có thể làm điều gì đó như:

<input type="password" name="repeatPassword" id="repeatPassword" placeholder="repeat password" ng-model="user.repeatPassword" repeat-password="password" required>

Tín dụng thuộc về tác giả


Sau một awful nhiều mucking xung quanh, đây là giải pháp tốt nhất đối với tôi khi sử dụng xác nhận thêm thuộc tính quá (ví dụ như độ dài tối thiểu, cần thiết, vv)
Carlos P

3

Điều này có đủ tốt không:

<input type="password" ng-model="passwd1" />
<input type="password" ng-model="passwd2" />
<label ng-show="passwd1 != passwd2">Passwords do not match...</label>
<button ng-disabled="passwd1 != passwd2">Save</button>

Đơn giản, và hoạt động tốt cho tôi.


1
Đây không phải là xác thực. biểu mẫu. $ hợp lệ sẽ bằng true.
Intellix

Chúng tôi có thể tắt nút Lưu, cho đến khi điều kiện mật khẩu được thỏa mãn (đã thêm tương tự ở trên).
Jasper,

Đây vẫn không phải là xác nhận thích hợp. Có toàn bộ hệ thống xác nhận, không sử dụng nó để lưu một vài dòng chỉ là điều ngớ ngẩn.
DennisK

Dennis Kr0ger> Nó hoạt động tốt .. Bạn có thể vui lòng chỉ ra những gì sai với nó?
Jasper

3

Giải pháp này tương tự như giải pháp do Dominic Watson đưa ra, sử dụng trình xác thực $ và là giải pháp tôi thích nhất. Những thay đổi duy nhất là bạn có thể xem một biểu thức.

$ validators Một tập hợp các trình xác thực được áp dụng bất cứ khi nào giá trị mô hình thay đổi. Giá trị khóa trong đối tượng đề cập đến tên của trình xác thực trong khi hàm đề cập đến hoạt động xác nhận. Thao tác xác thực được cung cấp với giá trị mô hình làm đối số và phải trả về giá trị đúng hoặc sai tùy thuộc vào phản hồi của xác nhận đó

từ https://code.angularjs.org/1.3.15/docs/api/ng/type/ngModel.NgModelController

Tôi đang sử dụng góc 1.3. Chỉ thị của tôi trông giống như thế này

angular.module('app').directive("passwordConfirm", function() {
    "use strict";
    return {
        require : "ngModel",
        restrict : "A",
        scope : {
            //We will be checking that our input is equals to this expression
            passwordConfirm : '&'
        },
        link : function(scope, element, attrs, ctrl) {
            //The actual validation
            function passwordConfirmValidator(modelValue, viewValue) {
                return modelValue == scope.passwordConfirm();
            }
            //Register the validaton when this input changes
            ctrl.$validators.passwordConfirm = passwordConfirmValidator;
            //Also validate when the expression changes
            scope.$watch(scope.passwordConfirm, ctrl.$validate);
        }
    };
});

Để dùng nó

<input type="password" ng-model="user.password"/>
<input type="password" ng-model="user.confirmPassword" 
                password-confirm="user.password" />

3

Để xác thực biểu mẫu với hai trường đầu vào, tôi tìm cách phù hợp nhất

Chỉ thị

app.directive('passwordVerify', function() {
return {
    require: 'ngModel',
    link: function (scope, elem, attrs, ctrl) {
        if (!attrs.passwordVerify) {
            return;
        }
        scope.$watch(attrs.passwordVerify, function (value) {
          if( value === ctrl.$viewValue && value !== undefined) {
             ctrl.$setValidity('passwordVerify', true);
             ctrl.$setValidity("parse",undefined);
          }
          else {
             ctrl.$setValidity('passwordVerify', false);
          }
        });
        ctrl.$parsers.push(function (value) {
            var isValid = value === scope.$eval(attrs.passwordVerify);
            ctrl.$setValidity('passwordVerify', isValid);
            return isValid ? value : undefined;
        });
    }
  };
});

HTML

     <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required || (form.password.$error.minlength || form.password.$error.maxlength)}">
              <input type="password" name="password" ng-minlength="6" ng-maxlength="16" id="password" class="form-control" placeholder="Password" ng-model="user.password" required />
              <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
              <span ng-show="form.password.$error.minlength || form.password.$error.maxlength" class="help-block">Password must be 6-16 character long</span>
          </div>
        </div>
       </div>
       <div class="row">
         <div class="col-md-10 col-md-offset-1">
           <div class="form-group" ng-class="{ 'has-error': (form.confirm_password.$dirty && form.confirm_password.$error.required) || form.confirm_password.$error.passwordVerify }">
              <input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password" ng-model="user.confirm_password" required password-verify="user.password" />
              <span ng-show="form.confirm_password.$dirty && form.confirm_password.$error.required" class="help-block">Confirm Password is required</span>
              <span ng-show="form.confirm_password.$error.passwordVerify" class="help-block">Please make sure passwords match & must be 6-16 character long</span>
          </div>
        </div>
      </div>

2

Điều này hoạt động theo cả hai cách và nó rất đơn giản và sạch sẽ

JavaScript

var app = angular.module("app");

app.controller("SamePaswordController", function () {

  this.password;
  this.confirm;

  this.save = function () {
    alert("Saved!");
  };
}


app.directive("match", function () {
  return {
    restrict:"A",
    require:"ngModel",

    link: function(scope, element, attrs, ctrl) {

      function matchValidator(value) {      

        scope.$watch(attrs.match, function(newValue, oldValue) {

          var isValid = value === scope.$eval(attrs.match);                    
          ctrl.$setValidity('match', isValid);

        });

        return value;
      }

      ctrl.$parsers.push(matchValidator);
    }
  };
});

HTML: lưu ý chỉ thị đối sánh

<form name="regForm" ng-controller="SamePaswordController as regCtrl"
      ng-submit="regForm.$valid && regCtrl.save()" novalidate>

  <input name="password" ng-model="regCtrl.password" 
         type="password" required placeholder="Password"/>                

  <input name="confirm" ng-model="regCtrl.confirm" match="regCtrl.password"
         type="password" required placeholder="Confirm password"/>


  <div> regForm is valid:{{regForm.$valid}}</div>

  <input type="submit" value="Save"/>

</form>

Bạn có thể sao chép repo bằng ví dụ này https://github.com/rogithub/roangularjs


Các phần hay là: scope. $ Watch, scope. $ Eval và match = "regCtrl.password".
Ro.

Điều này đã không làm việc cho tôi. Đồng hồ trên xác nhận các thay đổi và ví dụ tôi tin là không chính xác. match = {{regCtrl.password "}}
Enkode

2

Không phải là một giải pháp chỉ đạo nhưng đang làm việc cho tôi:

<input ng-model='user.password'
 type="password"
 name='password'
 placeholder='password'
 required>
<input ng-model='user.password_verify'
 type="password" 
 name='confirm_password'
 placeholder='confirm password'
 ng-pattern="getPattern()"
 required>

Và trong bộ điều khiển:

//Escape the special chars
    $scope.getPattern = function(){
        return $scope.user.password && 
              $scope.user.password.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1');
    }

http://plnkr.co/edit/QDTnipCsHdg56vgygsqC?p=preview


1

Sau đây là vấn đề của tôi. Chỉ thị này sẽ so sánh với giá trị biểu mẫu thay vì phạm vi.

'use strict';
(function () {
    angular.module('....').directive('equals', function ($timeout) {
        return {
            restrict: 'A',
            require: ['^form', 'ngModel'],
            scope: false,
            link: function ($scope, elem, attrs, controllers) {
                var validationKey = 'equals';
                var form = controllers[0];
                var ngModel = controllers[1];

                if (!ngModel) {
                    return;
                }

                //run after view has rendered
                $timeout(function(){
                    $scope.$watch(attrs.ngModel, validate);

                    $scope.$watch(form[attrs.equals], validate);
                }, 0);

                var validate = function () {
                    var value1 = ngModel.$viewValue;
                    var value2 = form[attrs.equals].$viewValue;
                    var validity = !value1 || !value2 || value1 === value2;
                    ngModel.$setValidity(validationKey, validity);
                    form[attrs.equals].$setValidity(validationKey,validity);
                };
            }
        };
    });
})();

trong HTML bây giờ người ta đề cập đến biểu mẫu thực thay vì giá trị trong phạm vi:

<form name="myForm">
  <input type="text" name="value1" equals="value2">
  <input type="text" name="value2" equals="value1">
  <div ng-show="myForm.$invalid">The form is invalid!</div>
</form>

Không có vẻ như các giá trị biểu mẫu có thể được xem vì vậy tôi nghĩ rằng $scope.$watch(form[attrs.equals], validate);nó không bao giờ thực sự được gọi. Nếu không, chỉ cần có equalsthuộc tính trên một phần tử là đủ.
Vadym

0

Để đạt được xác thực khi cả hai đầu vào thay đổi, tôi sử dụng mã sau (là sự kết hợp của tất cả các câu trả lời khác):

angular.module('app.directives')
.directive('passwordVerify', [function () {
    return {
        require: '?ngModel',
        restrict: 'A',
        scope: {
            origin: '=passwordVerify'
        },
        link: function (scope, element, attrs, ctrl) {
            if(!ctrl) {
                return;
            }

            function validate(value) {
                ctrl.$setValidity('passwordMatch', scope.origin === value);
                return value;
            }

            ctrl.$parsers.unshift(validate);

            scope.$watch('origin', function(value) {
                validate(ctrl.$viewValue);
            });
        }
    };
}]);

0

Trước tiên, tôi muốn cảm ơn Fredric đã đăng ví dụ tuyệt vời này. Có một vấn đề nhỏ mà tôi tình cờ gặp phải. trên Fiddle bạn đã đăng http://jsfiddle.net/gUSZS/

Nếu bạn nhập mật khẩu, sau đó nhập cùng một mật khẩu vào phần tử đầu vào xác minh, mọi thứ đều hoạt động tốt, nhưng hãy thử thêm khoảng trắng vào ô thứ hai và góc sẽ tự động cắt bớt khoảng trống đó. Điều này có nghĩa là chỉ thị không "nhìn thấy" không gian thừa. Bây giờ mật khẩu đã khác, nhưng biểu mẫu vẫn còn hiệu lực.

để khắc phục điều này, chúng tôi cần thêm

ng-trim="false"

đến các yếu tố đầu vào. Điều này không hoạt động trong góc 1.0.3 vì vậy nếu bạn muốn thử nó trong trò chơi này, bạn cần thêm 1.1.1 vào Fiddle ( http://ajax.googleapis.com/ajax/libs/angularjs/1.1.1/angular .js )

Nhưng một lần nữa, than Frederic, tôi sẽ sử dụng giải pháp của bạn trong ứng dụng của tôi!

Anton PS Tôi muốn nhận xét về bài đăng của Frederic, nhưng tôi là người mới tham gia diễn đàn này và dường như không có đủ tín dụng. Vì vậy, sẽ rất được đánh giá cao nếu một số bạn có thể bình chọn nhận xét của tôi nếu bạn thích nó :-)


0

Không cần thêm chỉ thị, đây là quyết định của tôi:

HTML:

<div class="form-group" data-ng-class="{ 'has-error': submitted && !form.new_passwd.$valid }">
    <input type="password" name="new_passwd" class="form-control" data-ng-model="data.new_passwd" placeholder="New Password" required data-ng-pattern="passwdRegex">
    <small class="help-block" data-ng-show="submitted && form.new_passwd.$error.required">New password is required!</small>
    <small class="help-block" data-ng-show="submitted && !form.new_passwd.$error.required && form.new_passwd.$error.pattern">New password is not strong enough!</small>
</div>

<div class="form-group" data-ng-class="{ 'has-error': submitted && !form.new_passwd_conf.$valid }">
    <input type="password" name="new_passwd_conf" class="form-control" data-ng-model="data.new_passwd_conf" placeholder="Confirm New Password" required data-ng-pattern="passwdConfRegex">
    <small class="help-block" data-ng-show="submitted && form.new_passwd_conf.$error.required">New password confirmation is required!</small>
    <small class="help-block" data-ng-show="submitted && !form.new_passwd_conf.$error.required && form.new_passwd_conf.$error.pattern">New password confirmation does not match!</small>
</div>

Javascript:

$scope.passwdRegex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,}$/;
$scope.$watch('data.new_passwd', function() {
    $scope.passwdConfRegex = new RegExp(Regex.escape($scope.data.new_passwd));
});

nơi Regex.escape () có thể được tìm thấy ở đây .

Hoạt động như một sự quyến rũ!


Tôi đã thử với jsfiddle không hoạt động, bạn có thể tập hợp lại và cho chúng tôi xem?
Nick Kahn

0

Để thêm vào số lượng lớn các giải pháp hiện có, điều này hoạt động tốt đối với tôi.

( Câu trả lời của Jan Laussmann đã ngừng hoạt động với các bản phát hành AngularJS beta mới nhất).

chỉ thị:

angular.module('myApp').directive('matchValidator', [function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attr, ctrl) {
                var pwdWidget = elm.inheritedData('$formController')[attr.matchValidator];

                ctrl.$parsers.push(function(value) {
                    if (value === pwdWidget.$viewValue) {
                        ctrl.$setValidity('match', true); 
                        return value;
                    }                       

                    if (value && pwdWidget.$viewValue) {
                        ctrl.$setValidity('match', false);
                    }

                });

                pwdWidget.$parsers.push(function(value) {
                    if (value && ctrl.$viewValue) {
                        ctrl.$setValidity('match', value === ctrl.$viewValue);
                    }
                    return value;
                });
            }
        };
    }])

sử dụng

<input type="email" ng-model="value1" name="email" required>
<input type="email" ng-model="value2" name="emailConfirm" match-validator="email" required>

lỗi hiển thị

<div ng-if="[[yourFormName]].emailConfirm.$error">
    <div ng-if="[[yourFormName]].emailConfirm.$error.match">
        Email addresses don't match.
    </div>
</div>

0
   <input name="password" type="text" required="" ng-model="password" placeholder="password" class="ng-dirty ng-valid ng-valid-required">
   <input name="confirm_password" type="text" required="" ng-model="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' " placeholder="confirm password" class="ng-dirty ng-valid-required ng-invalid ng-invalid-validator"> 
   <span ng-show="form.confirm_password.$error.validator">Passwords do not match!</span>
        password errors: {
        "required": false,
        "validator": true
        }

0

Điều này đã làm việc cho tôi.

Chỉ thị:

modulename.directive('passwordCheck', function () {

    return {
        restrict: 'A', // only activate on element attribute
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, elem, attrs, ngModel) {
            if (!ngModel) return; // do nothing if no ng-model

            var Value = null;

            // watch own value and re-validate on change
            scope.$watch(attrs.ngModel, function (val) {
                Value = val;


                validate();
            });

            // observe the other value and re-validate on change
            attrs.$observe('passwordCheck', function () {
                validate();
            });

            var validate = function () {

                // values
                var val1 = Value;
                var val2 = attrs.passwordCheck;

                // set validity

                if (val1 != '' && val1 != undefined) {
                    ngModel.$setValidity('passwordCheck', val1 == val2);

                }

                else {
                    ngModel.$setValidity('passwordCheck', true);
                }
            };
        }
    }
});

HTML:

ng-model="confirmpassword.selected" type="password" name="confirmpassword" 

password-check="{{password.selected}}"

ng-show="resetpasswordform.confirmpassword.$error.passwordCheck && submitted" Password does not match

0

Tôi đã gặp vấn đề tương tự khi cố gắng tạo chỉ thị của riêng mình và tôi đã khắc phục bằng phần bổ sung này

ctrl.$validate();

trong đó ctrl là ngModelController của tôi

đây là quan điểm của tôi

<input type="password" match="signupCtrl.registrationData.password" name="confirmPassword" class="form-control" placeholder="Confirm Password" data-ng-model="signupCtrl.registrationData.confirmPassword" required>
        <span ng-messages="registerForm.confirmPassword.$error">
            <span ng-message="match">The Password must match</span>
        </span>

đây là chỉ thị của tôi

(function () {
    'use strict';
    angular.module('matchDirective', [
        // Angular modules
        // Custom modules
        // 3rd Party Modules
    ]);
})(); 
(function () {
    'use strict';
    angular
        .module('matchDirective')
        .directive('match', match);
    match.$inject = ['$window'];

    function match($window) {
        // Usage:
        //     <element match="source"></element>
        // Creates:
        //
        var directive = {
            link: link,
            restrict: 'A',
            require: 'ngModel',
        };
        return directive;

        function link(scope, element, attrs, ctrl) {
            scope.$watch(attrs['match'], function (newVal, oldVal) {
                ctrl.$validators.match = function (modelValue, viewValue) {
                    if (newVal == modelValue) {
                        return true;
                    } else {
                        return false;
                    }
                }
                ctrl.$validate();
            });
        }
    }
})();

0

Một cái gì đó như thế này phù hợp với tôi:

js:

.directive('sameAs', function() { return {
    require : 'ngModel',
    link : function(scope, elm, attrs, ngModelCtrl) {

        ngModelCtrl.$validators.sameAs = function(modelValue, viewValue) {
            var checkedVal = attrs.sameAs;
            var thisInputVal = viewValue;

            if (thisInputVal == checkedVal) {
                return true; // valid
            } else {
                return false;
            }
        };
    }
}; });

html:

<input type="password" name="password" id="password" ng-model="password" />

<input type="password" name="passwordRepeat" id="passwordRepeat" 
    ng-model="passwordRepeat" same-as="{{password}}" />

0

Nguyên tắc Keep It Simple And Stupid (KISS) có thể hữu ích với nguyên tắc này. Nhanh hơn và dễ dàng hơn để kiểm tra xem cả hai mật khẩu có khớp nhau hay không bằng cách thực hiện như sau:

<div ng-app="app" ng-controller="passwordCheck">
  <form name="signUp" ng-submit="submitForm()" novalidate>
     <input type="password" name="password" ng-model="password" required>
     <input type="password" name="ConfirmPassword" ng-model="passwordconfirm"   required>
     <button type="submit"> Submit</button>
  </form>

  <hr>
  <span>Do they match?</span> {{signUp.password.$viewValue == signUp.confirmPassword.$viewValue}}
    </div>

Và Trước khi gửi biểu mẫu, bạn có thể làm điều này trong js của bạn

var app = angular.module("app", []);
app.controller("passwordCheck", function($scope) {
   $scope.submitForm = function() {
      if ($scope.signUp.$valid && $scope.signUp.password.$viewValue == $scope.signUp.confirmPassword.$viewValue) {
            alert('Its a match!');
        };
};
});

Bạn cũng có thể kiểm tra nó trong JSfiddle .

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.