AngularJS:根据输入的内容使无效

时间:2015-06-04 11:24:50

标签: angularjs controller html-form

在验证我的表单以获取密码时,我之前只需要输入密码字段,但现在我正在应用密码必须具有的字符数等条件,而且我似乎无法使这部分工作

我有这个功能,可以在用户输入时向用户显示正确的信息,

    $scope.$watch(
        function ($scope, $rootScope) {

            if ($scope.user.NewPassword != 'undefined') {
                if ($scope.user.NewPassword.length < 8) {
                    $scope.errorMessage = "Your password must contain more than 8 characters.";
                    $scope.validPassword = false;
                    return true;
                } else if (!authService.regExpPasswordValidation().exec($scope.user.NewPassword)) {
                    $scope.errorMessage = "Your password does not meet the minimum password complexity. Please make sure it contains at least 1 uppercase character, 1 lowercase character, 1 number, and 1 non-alphanumeric character.";
                    $scope.validPassword = false;
                    return true;
                } else {
                    $scope.validPassword = true;
                    return false;
                }
            }
        }
    );

问题在于,只要输入了任何内容,表单底部的提交按钮仍然可以点击,尽管错误信息显示正确,这是我不想要的。

以下是表单的相关部分,

<div class="form-group required" ng-show="!user.CtsAccount">
    <label for="inputPassword" class="col-sm-3 control-label">Password</label>
    <div class="col-sm-9">
        <input type="password" class="form-control" id="inputPassword" name="password" placeholder="Password" ng-required="!user.CtsAccount && FormTitle=='Add User'" ng-model="user.NewPassword">
    </div>
</div>

<div ng-show="!userForm.password.$pristine">
    <div class="alert alert-dismissible alert-warning" ng-show="!validPassword">
        <p>{{errorMessage}}</p>
    </div>
</div>

-

<div class="modal-footer">
    <button type="submit" ng-click="save()" ng-if="user.Id" ng-disabled="userForm.$invalid" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save User</button>
    <button type="submit" ng-click="add()" ng-if="!user.Id" ng-disabled="userForm.$invalid" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Add User</button>
    <button ng-click="cancel()" class="btn btn-default">Cancel</button>
</div>

有关实现这项工作的最佳方式的任何想法吗?

1 个答案:

答案 0 :(得分:1)

这很简单。对于ng-disabled以及表单无效属性,您还可以将$scope.validPassword检查为以下。

以下是编辑过的代码:

<div class="modal-footer">
    <button type="submit" ng-click="save()" ng-if="user.Id" ng-disabled="userForm.$invalid || !$scope.validPassword" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save User</button>
    <button type="submit" ng-click="add()" ng-if="!user.Id" ng-disabled="userForm.$invalid || !$scope.validPassword" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Add User</button>
    <button ng-click="cancel()" class="btn btn-default">Cancel</button>
</div>