Tips for showcasing server side validation error messages on a form using AngularJS

Utilizing AngularJS and Spring MVC in my current project, I am sending JSON to a rest controller for field validation. In the event of a validation failure, an Error object is returned containing details such as:

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

My concern now is how to display inline error messages on the JSP page.

Here is a snippet of my JSP code:

   <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" />

            //I need to show inline error message here
</div> 

As for my JavaScript code:

//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);

  };
}]);

Answer №1

After reviewing your code:

All validation errors are stored in :

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

Instead of _showValidationErrors, the recommended approach is:

$scope.errors = data.validationErrors;

In your HTML file:

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

    //Inline error message will be displayed here

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

To clear errors: within

$scope.loginSubmit = function(user) {

    $scope.errors = []; // reset errors

UPDATE: // based on feedback

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to incorporate two ng-repeat directives within a single td element in a table?

The results so far Expected outcome Please advise me on how to incorporate two ng-repeats within one td. When I use a span tag afterwards, the expected result is not achieved. I have used one ng-repeat in the td and the other in a span tag, which is why t ...

Is there a way to modify the colors of particles in GPUParticleSystem with Three.js?

I have encountered an issue where I am trying to add black particles in a white THREE.scene. Despite changing the spawn option color, there are still white particles present as if there is a base particle spawn color. The problem arises when I set a white ...

Tips on sending form data, including a file, to Ajax using the onclick() method

My Modal Includes a Form: <div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content"> <div class="modal-dialog modal-lg" role="document"> ...

Using AngularJS to recycle computed variables

In my template, I am in need of utilizing a calculated value to hide certain elements and perform other actions. <button ng-hide="expensive()" ng-click="foo()">foo</button> <button ng-show="expensive() && otherFunction()" ng-click=" ...

Steps for triggering a function when the 'Enter' key is pressed in a TextInput in a React Native application

I'm currently working on creating a Search Bar feature. I would like the user to input text into the TextInput field, and when they press 'Enter', I want it to trigger my function. <TextInput //when the user presses Enter, call the functi ...

Having trouble displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

AngularJS - Determine the correct condition or make a choice from the available options

I'm having trouble figuring out how to save the option I select to a viewmodel. The ng-model should save whatever option I choose, and if nothing is selected, the value should default to "Select One." The available options are YES (true) / NO (false). ...

Discovering the vacant fields within a database by looping through them

My goal is to download a .pdf document from the external database Contentful by utilizing an HTML link on a user interface. The issue arises when certain fields inside Contentful do not always necessitate a pdf document. In these cases, the field remains ...

Lazy loading a React grid gallery as you scroll

Currently, I am utilizing React grid gallery to showcase images from this repository: https://github.com/benhowell/react-grid-gallery. However, I am encountering an issue with lazy loading when the user scrolls on the page. <Gallery images={this ...

What is the method for providing a date format choice in JSON?

I am encountering an issue in my PHP script where I use JSON to pass parameters. When I pass the date as "09-09-2015", it functions correctly. However, when I try to pass the date as $date, it does not work. How can I resolve this problem? $item1 = "test ...

What is the best way to limit angular-xeditable to accept only positive numbers?

This is my code snippet. I'm looking for an attribute that will only allow positive numbers to be entered. <td><span e-step="0.001" editable-number="myNumber" onaftersave="updateValue()">{{ myNumber }} </span></td> ...

What is the best way to transfer data from a div tag to an li tag using JavaScript?

https://i.stack.imgur.com/se2qk.pngI am attempting to change the div tag content to li tag. Here is a snippet of the code from inspect for reference. I need to remove the div tag with the "domTitle" class. <li style="display: inline;" id="list_name"> ...

Exploring the contrasts in values within the ng-repeat directive of AngularJS

I am currently working with a JSON object that contains information about various clients, including the payments made over different date ranges within each month. My goal is to loop through this list of customers and display a table for each customer, hi ...

Using Material UI with Reactjs for Background Image Mapping

I need some advice from everyone. I have an array of images and I've mapped the content, but for some reason I am unable to set a background image in the styles of a component. The other objects in the array are working as expected. {DlCards.map((mdlc ...

Encountering an NPM error while attempting to initiate a new React application

Having trouble creating a React app due to an npm warning message? Seek assistance, please! npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19342d2e6a6867687c4b">[email protected]</a>: This ve ...

Combining the powers of Nextjs and Vue

Currently utilizing Vue.js, I am now looking to leverage the Next.js framework for its SEO capabilities, server-side rendering features, and other advantages. While I do have some experience with React, my primary focus is on mastering Vue.js. Is it poss ...

Validating numbers in React JS input fields component

I need assistance with implementing number validation for 3 Textfields in my application. Currently, the code displays an error message if a Textfield is empty, but I am stuck on validating whether the input is text or numbers. import React from 'rea ...

Adjust the position if the height exceeds 100 pixels

Can someone help with this code issue? $(document).ready(function () { if ($('.pi-img').height() > 100) { $(this).css('top' , '30%'); console.log('yeah'); } }); I am encountering difficu ...

Angular Error TS2339: The property 'car' is missing from type 'Array of Vehicles'

Encountering Angular Error TS2339: Property 'vehicle' is not found on type 'Vehicle[]'. The error is occurring on data.vehicle.results. Any thoughts on what could be causing this issue? Is the problem related to the Vehicle model? I hav ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...