Flag form field as invalid in AngularJS

Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message?

Here's the setup of my app:

I have a model 'client' with a controller

Accounts.controller('Client', ['$scope', 'ClientService', function ($scope, ClientService) {
    $scope.loading = false;
    $scope.errors = null;

    $scope.init = function () {
         $scope.abn = "some value from API call";
    };

    $scope.save = function (client) {
            $scope.form.abn.$setValidity("server", false);
            $scope.errors.abn = "Error message";
    }

    $scope.init();
}]);

and a form view

<form name="form">
    <div class="form-group">
        <label>ABN Number</label>
        <input type="text" name="abn" ng-model="client.abn">
        <span ng-show="form.abn.$error.server">{{client.errors.abn}}</span>
    </div>
    <button ng-click="save(client)">Save</button>
</form>

and an app like so

var Accounts = angular.module('Accounts', [
    'ngRoute',
    'ui.select2',
    'ui.router'
])
.config(function ($stateProvider, $routeProvider) {
    $routeProvider.otherwise('/404');

    $stateProvider
        .state('client', {
            url: "/client",
            templateUrl: "client",
            controller: 'Client'
        })
        .state('404', {
            url: "/404",
            templateUrl: "/error/e404/"
        });

});

Need help setting the abn field as invalid and displaying an error message? Looking for guidance on this issue.

Answer №1

To properly showcase the error, follow these steps:

Replace $error.server with $invalid:

<span ng-show="form.abn.$invalid">{{client.errors.abn}}</span>

I have included a style for the ng-invalid class and created a plunkr where the field turns red and displays an errorMessage when you click on the save button. Additionally, there was an issue with setting a property on $scope.errors since it was null.

http://plnkr.co/fDWF5g

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

Basic parallax application, failing to achieve the desired impact

My goal is to create a scrolling effect where the header text moves down slightly, adding some margin on top to keep it in view. I found the perfect example of what I want to achieve with the header text at this website: After spending hours working on i ...

Hovering over a table cell triggers a popup in Angular

Inserted a class into <td><span class="only-show-on-hover"></span></td> CSS code for the class td span.only-show-on-hover { visibility: hidden; } td:hover span.only-show-on-hover { visibility: visible; } Code for dialog box < ...

Did I accidentally overlook a tag for this stylish stripe mesh Gradient design?

I've been attempting to replicate the striped animated Gradient mesh using whatamesh.vercel.app. I've set up the JS file, inserted all the gist code into it, and placed everything in the correct locations, but unfortunately, it's not functio ...

Organize data by multiple criteria using List.js

Attempting to configure the list.js plugin to allow sorting based on multiple values. Specifically, the goal is to sort by category first and then alphabetically by title within each category. See a demo here: http://jsfiddle.net/8E7cH/ This functional ...

Guide on seamlessly adding NPM "dependencies" to index.html using <script> tags in a VUE JS WEBPACK project

Are there any tools available that automatically inject or include NPM dependencies into the index.html file, similar to the GRUNT-BOWER plugin for BOWER dependencies? The project in question is a VUE-CLI WEBPACK project. Can this functionality be achieve ...

What is the best way to receive data from an asynchronous server-side Java Controller?

After doing some research, I found several examples, including using $q from Angular to prevent making repeated server calls to check if a request is complete with data. One of the resources I came across is this link: Recursive $http.get in for loop Alt ...

Contrast between using "export { something }" and "export something" in JavaScript modules

Can you explain the difference between the following code snippets: import something from "../something"; export { something }; vs import something from "../something"; export something; I noticed in the react-is package from react, there is an export ...

Eliminate unnecessary words from the sentence

I wrote a sentence but it got split at every space. The data is displayed like this: const escapeRE = new RegExp(/([/\?""])/g); const myDatas = data.map(des => des.Sentence.toLowerCase().replace(escapeRE, '').split(' ')); [ [ ...

What is the method to create a polygon in its entirety by utilizing a for loop within Javascript?

After successfully using the Canvas of HTML to draw a convex polygon, I encountered an issue. In the provided code snippet, t2 represents an array of points with getX() and getY() methods. The drawing function performs as expected until it reaches the seg ...

What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11 Trying to set up in main.js as follows: import moment from 'moment' moment.locale('nl'); Object.definePrototype(Vue.prototype, '$moment', { value: moment }); Encountering an error ...

JavaScript Loading Screen - Issues with window.onload functionality

I am currently working on creating a loading screen for my project. I need to use JavaScript to remove the CSS property "Display: none" from the page, but for some reason, my code is not functioning as expected. The Issue: I discovered that using window. ...

Persisting dynamically generated table information into a multidimensional array

I've created a dynamic table and now I'm trying to extract the data from it and store it in a multidimensional array. However, I keep encountering an exception/error that says "Cannot set property of 0 to undefined". https://i.sstatic.net/W8B9j.p ...

Tips for preventing redundant data entry in a table

Currently, my table displays like so: The structure of the HTML for the table is as follows (only a snippet is shown, as the rest looks similar): <table class="table table-bordered table-condensed"> <tr> <th>Days</th> ...

What's the reason behind the failure of bitwise xor within a JavaScript if statement?

I'm trying to understand the behavior of this code. Can anyone explain it? Link to Code function checkSignsWeird(a,b){ var output = ""; if(a^b < 0){ output = "The "+a+" and "+b+" have DIFFERENT signs."; }else{ output = ...

Struggling to make PayPal Cordova Plugin function properly in both production and sandbox modes

While using the cordova paypal plugin and switching to sandbox mode, I encountered an error. The plugin can be found at https://github.com/paypal/PayPal-Cordova-Plugin https://i.stack.imgur.com/lD2EH.png Running the plugin in PayPalEnvironmentNoNetwork m ...

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

Bidirectional binding of attributes in an Angular directive

I have developed a custom Angular Directive known as evoEventMirror. Its main purpose is to attach a jQuery event to an inserted element and apply a specified CSS style to the "root" element. Refer to the example below: <div id="#mydiv" evo-event-mirro ...

Error: The requested resource does not have the 'Access-Control-Allow-Origin' header. The request is successful, but an error is being triggered

As I am trying to make an Ajax cross domain request, I have come across a strange issue. In the console of Chrome dev tools, I see the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource" Despite this ...

What sets $(document).on apart from ($ document).on in CoffeeScript?

One of my buddies is incorporating ($ document).on into his CoffeeScript script. I'm curious to know if this differs from the typical $(document).on and, if it does, how so? ...

Utilize web workers for efficient processing of a limited number of files simultaneously in JavaScript

Utilizing the web worker concept for file uploads has resulted in creating a web worker for each selected file. The idea now is to optimize this process by creating 5 web worker threads to handle the first batch of five files, terminating them afterwards b ...