I am using AngularJS and Spring MVC in my project. In this, I am sending JSON to rest controller which validate fields and return Error object in case of validation failure as follows:
{"validationErrors":[
{
"errorCode":"emailId",
"errorDescription":"Please enter email address."
}
]}
Now, on jsp how to display inline error message?
My jsp code is as follows:
<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>
And my js code is: //Updated 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);
};
}]);
As per your code:
The validation errors are captured in :
error(function(data, status, headers, config) {
_showValidationErrors($scope, data.validationErrors);
});
So instead of _showValidationErrors
, use
$scope.errors = data.validationErrors;
Now in your 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>
To reset errors : inside your
$scope.loginSubmit = function(user) {
$scope.errors = []; // reset errors to empty array
EDIT: // as per comment
To show specific error messages:
$scope.getErrorMessage = function(errorCode) {
var error;
$scope.errors.forEach(function(error) {
if(error.errorCode === errorCode) {
error = error.errorDescription;
}
});
return error;
}
Now in your 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>