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

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...

Encountering status code 0 when handling 413 (Request Entity Too Large) error in AngularJS with Loopback API

1. Revealing Some Details In my client-side application built with AngularJS 1.3.15, I am utilizing a loopback API for handling requests. Within the application, I have set up interceptors using $httpProvider.interceptors to interpret status codes and di ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

One text label to display for a MultiLineString using MapLibre GL JS

I am attempting to show text labels for MultiLineString features within a geoJSON file using MapLibre GL JS. By utilizing the symbol-placement: point option, I aim to display the labels across various zoom levels rather than only when extremely close, as w ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...

Looking to utilize vue.js to alter the color of the <li> element when a select option is chosen

I'm a beginner in vue.js and I'm attempting to change the background color by using the select option. Despite trying the cueCardsColor method, nothing seems to be happening. <ul> <li :class="+ cueCardColor"> <sele ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

Having issues with my AngularJS application not updating as expected

After creating a custom service to store all search parameters, I can easily access them from any part of my code. This ensures that the search parameters are always accurate. Below is the definition of the custom service: App.factory('filterService& ...

Countdown to redirect or exit on Jquery mobile "pageshow" and "pagehide" events

Looking to implement a 30-second countdown on a Jquery Mobile page with specific requirements: (1) Countdown begins on pageshow (2) Redirects to new page when countdown expires (3) If user navigates away (pagehide) before countdown finishes, the timer fun ...

Having difficulty ensuring DayJs is accessible for all Cypress tests

Currently embarking on a new Cypress project, I find myself dealing with an application heavily focused on calendars, requiring frequent manipulations of dates. I'm facing an issue where I need to make DayJs globally available throughout the entire p ...

transmitting modifications to the model

Currently in the process of setting up a small POC to test the viability of using angular for a specific project. I have established a REST server that I can perform CRUD operations on using angular. However, due to the scattered documentation and tutoria ...

effective method for iterating through JSON data using JavaScript or jQuery

Upon receiving a JSON object from the server, it looks like this: { "0": { "id": "1252380", "text": "This whole #BundyRanch thing stinks to high hell. Can it be a coincidence that Harry Reid n his son have a financial interest in this land?", ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

Angular JS returned a 405 Error code in response to the preflight request

I'm currently making an API call across domains and encountering a specific response in Chrome. Even though I have all the necessary headers included in my REST API on the other domain, I am still facing this issue. <add name="Access-Control-All ...

Hover over a ListItem

Looking for advice on how to incorporate a Mouseover feature into a Material UI ListItem from the following link: http://www.material-ui.com/#/components/list. As the "SecondaryText" is limited to 2 lines, I am exploring options to display additional data ...

The CSS class is specifically assigned to a single element

After every two seconds, my JavaScript function is triggered and based on certain logic, I aim to add a CSS class with an effect to an HTML element on the page. var counter = 0; $interval(function () { counter++; ...

Add a fading transition feature to images that are loaded at a later time

I used a clever technique to create a blur effect by loading a small, lightweight image first. Once the main background image is loaded, it swaps out the 'data-src' with the actual image. However, I am facing an issue with the abrupt transition, ...

Is there a way to call class methods from external code?

I am seeking clarification on Class files. Below is an example of a Class that I have: class CouchController { constructor(couchbase, config) { // You may either pass couchbase and config as params, or import directly into the controller ...

Activate simultaneous HTML5 videos on iOS devices with a simple click

I am currently in the process of developing a webpage that will play various videos when specific elements are clicked. Although the functionality works perfectly on desktop computers, it encounters an issue on iOS devices. The problem arises when the elem ...

A step-by-step guide on how to implement a window scroll-controlled color transition

I've implemented jQuery code to change the opacity of my navbar's background as the user scrolls, transitioning from transparent to blue. Here's the snippet: $(window).scroll(function(){ var range = $(this).scrollTop(); var limit = 45 ...