如果两个字段不匹配,则会出现角度形式错误

时间:2014-06-18 16:04:35

标签: javascript forms angularjs

如果两个输入不匹配(如密码),是否有办法使表格无效?与form.password.$error.required相似?

2 个答案:

答案 0 :(得分:5)

 pwd1:<input type="password" ng-model="pwd1" required /><br />
 pwd2:<input type="password" ng-model="pwd" required /><br />

      <div ng-show="pwd1 && pwd">Invalid:
        <span ng-show="pwd1!==pwd">Wrong</span>
        <span ng-show="pwd1===pwd">Correct</span>
      </div>

这只是检查两个密码是否相同。 Angular Form validation

同时检查具有密码匹配指令

Angular Ui

答案 1 :(得分:3)

您可以使用Angular UI,它有一个ui-validate指令:

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

或者,您可以为该

构建自己的指令
myApp.directive('matchPassword', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        scope: {
            matchPassword: '='
        },
        link: function (scope, elem, attrs, ctrl) {
            scope.$watch(function () {
                return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || scope.matchSenha === ctrl.$modelValue;
            }, function (currentValue) {
                ctrl.$setValidity('matchPassword', currentValue);
            });
        }
    };
});

并像这样使用它:

<input required name="passwordConfirm" match-password="model.Password" />