如何在带有角度js的表单上显示服务器端验证错误消息

时间:2015-03-04 11:45:55

标签: javascript angularjs spring jsp spring-mvc

我在我的项目中使用AngularJS和Spring MVC。在此,我将JSON发送到rest控制器,该控制器验证字段并在验证失败的情况下返回Error对象,如下所示:

{"validationErrors":[
    {
        "errorCode":"emailId",
        "errorDescription":"Please enter email address."
    }
]}

现在,在jsp上如何显示内联错误消息?

我的jsp代码如下:

   <label ng-model="emailLbl" for="userEmailID">Email ID</label>
   <input type="email" ng-model="user.emailId" name="emailId" id="userEmailID" placeholder="Enter your email ID" />

            //Here, I want to display inline error message
</div> 

我的js代码是: //更新     angular.module('MiniApp',[]);

angular.module('MiniApp').controller('loginCtrl', ['$scope', '$http','$location',function($scope,$http,$location) {

    $scope.loginSubmit = function(user) {
   $scope.errors = [];
  $scope.jsonObject = angular.copy(user);
var data1;
setTimeout(function(){ 
    data1=document.getElementById("hiddenJson").value;
    $http({
        method: 'POST', 
        url: 'register1/login',
        headers: {'Content-Type': 'application/json'},
        data: data1
    }).
success(function(data, status, headers, config) {
    alert('Success:'+data.prospectResponseDetails.emailId+" - "+status);
    $location.path('WEB-INF/pages/login-step1.jsp');
}).
error(function(data, status, headers, config) {
    _showValidationErrors($scope, data.validationErrors);
    $scope.errors = data.validationErrors;

});

    $scope.getErrorMessage = function(errorCode) {
       var error;
       $scope.errors.forEach(function(error) {
         if(error.errorCode === errorCode) {
           error = error.errorDescription;
         }
       });
       return error;
    }
}, 200);

  };
}]);

1 个答案:

答案 0 :(得分:1)

根据您的代码:

验证错误记录在:

error(function(data, status, headers, config) {
        _showValidationErrors($scope, data.validationErrors);
   }); 

因此,请使用

而不是_showValidationErrors
$scope.errors = data.validationErrors;

现在在您的HTML中:

 <input type="email" ng-model="user.emailId" name="emailId" id="userEmailID" placeholder="Enter your email ID" />

    //Here, I want to display inline error message

   <ul ng-if="errors.length > 0">
      <li  ng-repeat="error in errors">{{error.errorCode}} {{error.errorDescription}}</li>
  </ul>
</div> 

重置错误:在

$scope.loginSubmit = function(user) {

    $scope.errors = []; // reset errors to empty array

编辑://根据评论

显示特定的错误消息:

$scope.getErrorMessage = function(errorCode) {
   var error;
   $scope.errors.forEach(function(error) {
     if(error.errorCode === errorCode) {
       error = error.errorDescription;
     }
   });
   return error;
}

现在在您的HTML中:

<input type="email" ng-model="user.emailId" name="emailId" id="userEmailID" placeholder="Enter your email ID" />

<div ng-if="getErrorMessage('emailId')">
    {{getErrorMessage('emailId')}}
</div>