【问题标题】:Client side and server side error message display for AngularJs FormAngularJs 表单的客户端和服务器端错误消息显示
【发布时间】:2015-07-17 20:19:32
【问题描述】:

我需要为客户端验证错误显示不同的消息,例如所需的消息 (This Field is Required) 和来自后端的服务器端错误消息,例如 (Entered Password is incorrect)。

我现在在做什么—— 在myController.js:我设置$scope.message = "This Field is Required";当用户没有给出任何值并尝试提交时,会显示上述错误。

但是一旦他给出了值,它就会去服务器检查它是否有效,如果它无效,服务器会返回另一个错误消息,即Entered Password is incorrect作为响应。

因此,如果我将此响应值设置为我的$scope.message,它会覆盖以前的值并正确显示,但我的问题是,如果用户尝试使用空白值提交,则会显示被覆盖的错误消息。但在这里它应该显示所需的消息,即This Field is Required

如何实现?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您可以创建一个自定义 Angular 指令来验证服务器上的密码。如果有任何错误,请在$validators 管道中添加错误。

    示例:创建一个指令来检查用户名可用性

    ngModule.directive('usernameAvailableValidator', ['$http', function($http) {
      return {
        require : 'ngModel',
        link : function($scope, element, attrs, ngModel) {
          ngModel.$asyncValidators.usernameAvailable = function(username) {
            return $http.get('/api/username-exists?u='+ username);
          };
        }
      }
    }])
    

    HTML:

    <form name="myForm">
    <!-- 
      first the required, pattern and minlength validators are executed
      and then the asynchronous username validator is triggered...
    -->
    <input type="text"
           class="input"
           name="username"
           minlength="4"
           maxlength="15"
           ng-model="form.data.username"
           pattern="^[-\w]+$"
           username-available-validator
           placeholder="Choose a username for yourself"
           required />
    <div ng-if="myForm.colorCode.$error.usernameAvailable">Error Message HERE!</div>
    </form>
    

    【讨论】:

    • 但是我想在用户点击提交后进行验证和http请求。对我有什么帮助?
    • 为此,将对网络的调用包装在服务/工厂内。当用户单击提交按钮时,将 (bool) 结果捕获到变量 [$scope.usernameAvailable = API 的结果]。然后在 html 模板中,用 ng-if="usernameAvailable" 切换 ng-if="myForm.colorCode.$error.usernameAvailable"。
    • 我还是不清楚。你能用例子解释一下吗?我是 Angular 的新手。对我来说有很多未知数:(
    猜你喜欢
    • 2017-09-30
    • 2013-04-16
    • 2021-09-04
    • 2018-03-03
    • 2012-12-19
    • 2013-03-18
    • 2019-10-05
    • 2020-12-26
    • 1970-01-01
    相关资源
    最近更新 更多