簡體   English   中英

Angular.js的密碼匹配

[英]Password Match with Angular.js

我嘗試創建一個帶有驗證的表單。 我是angular.js的新手。 我從示例中復制了一些代碼,但是無法正常工作。

這是我的html和腳本:

<body ng-app="myApp">
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
    <h2>Validation Example</h2>
    <form name="myForm" novalidate>
        <p>Username:<br>
        <input type="text" name="user" ng-model="user" required>
        <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
            <span ng-show="myForm.user.$error.required">Username is required.</span>
        </span>
        </p>

        <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
            <span ng-show="myForm.email.$error.required">Email is required.</span>
            <span ng-show="myForm.email.$error.email">Invalid email address.</span>
        </span>
        </p>

        <label for="password"> Password</label> 
        <input type="password" name="password" ng-model="password" placeholder="New Password"/>  
        <label for="confirmPassword">Confirm Password</label> 
        <input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>
        <span class="error" ng-show="myForm.password.$error.pwmatch"> Passwords don't match. </span>
        <p>
        <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid || myForm.email.$dirty && myForm.email.$invalid">
        </p>
    </form>

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

    app.directive('pwCheck', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attrs, ctrl) {
                scope.$watch(attrs.pwCheck, function (confirmPassword) {
                    var isValid = ctrl.$viewValue === confirmPassword;
                    ctrl.$setValidity('pwmatch', isValid);
                });
            }
        }
    });
    </script>
</body>

誰能告訴我這是怎么了?

據我對這個指令的了解,@ dcodesmith的解決方案基本上是正確的。 試試這個:

<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword" pw-check="password"/>

UPDATE。 對不起,以前的代碼段。 看一下這個。 這有效:

<input type="password" name="password" ng-model="password" placeholder="New Password"  pw-check="confirmPassword"/>

<input type="password" name="confirmPassword" placeholder="Confirm Password" ng-model="confirmPassword"/>

JS

link: function (scope, elem, attrs, ctrl) {
  scope.$watch(attrs.pwCheck, function (password) {
    var isValid = ctrl.$viewValue === password;
    ctrl.$setValidity('pwmatch', isValid);
  });
}

JSBin: http ://jsbin.com/rakivadibi/1/edit?html,js,輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM