Angularjs 中密码不匹配时如何显示错误消息?

How to display error message when passwords doesn't match in Angularjs?

我是 Angularjs 的新人,我的问题是当密码与确认密码不匹配时如何显示错误消息? 有人可以帮助我吗,这不是很困难,但我仍在学习编程。 谢谢大家! 我有 html 代码:

<form ng-submit="saveItem(userForm.$valid)" name="userForm">
    <div class="row">
        <div class="col-sm-6">
            <div class="form-group">
                <label for="database_address">User</label>
                <input type="text" class="form-control" required ng-model="activeItem.username" placeholder="Потребителско Име..." />
            </div>

            <div class="form-group">
                <label for="password">Password</label>
                <input type="text" class="form-control" id="password" ng-model="activeItem.passwordString"  />
            </div>
            <div class="form-group">
                <label for="password">Confirm Password</label>
                <input type="text" class="form-control" id="password" ng-model="activeItem.passwordConfirm"  />
            </div>
              <p ng-show="(userForm.passwordConfirm != '') && (userForm.password != userForm.passwordConfirm)">Passwords don't match</p>

        </div>
        <div class="col-sm-6">
            <div class="form-group">
                <label for="username">Operator</label>
                <input type="text" class="form-control" required id="username" ng-model="activeItem.name" />
            </div>
        </div>
    </div>
    <button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Save</button>
    <!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>

和angular函数:

$scope.saveItem = function(){
        console.log($scope.activeItem);
        //delete $scope.activeItem.hash_method
        var objectToSave = {
            username: $scope.activeItem.username,
            //password: $scope.activeItem.password,
            name: $scope.activeItem.name,
            id: $scope.activeItem.id
        };

        if($scope.activeItem.passwordString != ''){
            if($scope.activeItem.passwordString == $scope.activeItem.passwordConfirm){
                objectToSave.password = $scope.activeItem.passwordString;
            } else {
                    console.log('Confirm password error');

            }
        }

记住 'not equal' 的运算符是“!==”,这样你就可以做到!

您需要为两个密码字段保留不同的 ID,同时查看您的模型绑定:

<input type="text" class="form-control" id="password" ng-model="activeItem.passwordString" />

<input type="text" class="form-control" id="passwordConfirm" ng-model="activeItem.passwordConfirm" />

您可以在 ng-if/ng-show 中引用与 ng-model 绑定的项目,然后您不需要在后端使用任何自定义逻辑。

<p ng-show="(activeItem.passwordString && activeItem.passwordConfirm) && activeItem.passwordString !== activeItem.passwordConfirm ">Passwords don't match</p>

此外,您可能希望使用“!==”而不是“!=”,因为您只是比较两个字符串,因为它的比较更严格。

编辑:需要注意一件事,在这个方向上,您可能仍然希望在保存功能中进行错误检查,但这应该可以毫无问题地显示错误消息。