Tips for implementing validation in the given AngularJS code

What is the correct way to implement validations in AngularJS as shown in the CODE snippet below? I have attempted to apply the validations mentioned in the code but they seem to be malfunctioning. Please help me identify the error in the code related to validations.


<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
<script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript">
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope , $http) {
        refreshData();

        function refreshData(){
            $http({
                method: 'GET',
                url:'http://localhost:8081/SpringWithAngularJs/rest/countries.json'
                    }).success(function(data)
                        {

                        $scope.posts = data;

                        });
        }
        $scope.form = {
                countryName : "pp",
                population : "1000"
                    };
        $scope.add=function(){
            $http({
                method: 'POST',
                url:'http://localhost:8081/SpringWithAngularJs/rest/countries/create/'+$scope.form.countryName+'/'+$scope.form.population
                }).success(function(data){
                    refreshData();
                    });
            }
        $scope.remove=function(data){
            $http({
                method: 'DELETE',
                url:'http://localhost:8081/SpringWithAngularJs/rest/countries/delete/'+data
                }).success(function(data){
                    alert('Country Deleted');
                    refreshData();
                    });
        }
    });
    </script>
    </head>
<body ng-controller="myCtrl">
<form name="myForm" novalidate>
<h1>Country List</h1>
    <table border="">
        <thead>
            <tr>
                <th>Country Id</th>
                <th>Country Name</th>
                <th>Country Population</th>
                <th>Action</th>
            </tr>
        </thead>

        <tr ng-repeat="c in posts">
            <td>{{c.countryId}}</td>
            <td>{{c.countryName}}</td>
            <td>{{c.population}}</td>
            <td><button ng-click="remove($index)">Remove</button></td>
        </tr>
    </table>

    <h1>Add Country</h1>
    <table>
        <tr>
            <td>Country Name:</td>
            <td><input type="text" ng-model="form.countryName" required/></td>
            <td><span style="color: red" ng-show= "myForm.form.countryName.$dirty && myForm.form.countryName.$invalid">
            <span ng-show="myForm.form.countryName.$error.required">Country Name is required</span></span></td>
        </tr>

        <tr>
            <td>Country Population:</td>
            <td><input type="text" ng-model="form.population"/></td>
            <td><span style="color: red" ng-show= "myForm.form.population.$dirty && myForm.form.population.$invalid">
            <span ng-show="myForm.form.population.$error.required">Country Name is required</span></span></td>
        </tr>

        <tr>
            <td><button type="submit" ng-disabled="myForm.form.countryName.$dirty && myForm.form.countryName.$invalid || myForm.form.population.$dirty && myForm.form.population.$invalid" ng-click="add()">Add</button></td>
        </tr>

    </table>
    </form>
</body>
</html>

Alternatively, how can I effectively troubleshoot and debug any errors in the code?

Answer №1

Html Changes to be Aware Of -

Don't forget to include the necessary tag for population. Additionally, Angular validation relies on

the input name tag

   <td><input type="text" name="countryName" ng-model="form.countryName" required/></td>
            <td><span style="color: red" ng-show= "myForm.countryName.$dirty && myForm.countryName.$invalid">

   Country Name is required</span></td>

For the button -

<td><button type="submit" ng-disabled="myForm.$invalid" ng-click="add()">Add</button></td>

Answer №2

Failure to assign a name to the control and improper usage of formName.ControlName for error display. Instead of formName.ModelName, refer to my code snippet below.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="ISO-8859-1">
<title>Index</title>
<script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript">
    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope , $http) {
        refreshData();

        function refreshData(){
            $http({
                method: 'GET',
                url:'http://localhost:8081/SpringWithAngularJs/rest/countries.json'
                    }).success(function(data)
                        {

                        $scope.posts = data;

                        });
        }
        $scope.form = {
                countryName : "pp",
                population : "1000"
                    };
        $scope.add=function(){
            $http({
                method: 'POST',
                url:'http://localhost:8081/SpringWithAngularJs/rest/countries/create/'+$scope.form.countryName+'/'+$scope.form.population
                }).success(function(data){
                    refreshData();
                    });
            }
        $scope.remove=function(data){
            $http({
                method: 'DELETE',
                url:'http://localhost:8081/SpringWithAngularJs/rest/countries/delete/'+data
                }).success(function(data){
                    alert('Country Deleted');
                    refreshData();
                    });
        }
    });
    </script>
    </head>
<body ng-controller="myCtrl">
<form name="myForm" novalidate>
<h1>Country List</h1>
    <table border="">
        <thead>
            <tr>
                <th>Country Id</th>
                <th>Country Name</th>
                <th>Country Population</th>
                <th>Action</th>
            </tr>
        </thead>

        <tr ng-repeat="c in posts">
            <td>{{c.countryId}}</td>
            <td>{{c.countryName}}</td>
            <td>{{c.population}}</td>
            <td><button ng-click="remove($index)">Remove</button></td>
        </tr>
    </table>

    <h1>Add Country</h1>
    <table>
        <tr>
            <td>Country Name:</td>
            <td><input type="text" ng-model="form.countryName" name="countryName" required/></td>
            <td><span style="color: red" ng-show= "myForm.countryName.$dirty && myForm.countryName.$invalid">
            <span ng-show="myForm.countryName.$error.required">Country Name is required</span></span></td>
        </tr>

        <tr>
            <td>Country Population:</td>
            <td><input type="text" ng-model="form.population" name="population"/></td>
            <td><span style="color: red" ng-show= "myForm.population.$dirty && myForm.population.$invalid">
            <span ng-show="myForm.population.$error.required">Country Name is required</span></span></td>
        </tr>

        <tr>
            <td><button type="submit" ng-disabled="myForm.form.countryName.$dirty && myForm.form.countryName.$invalid || myForm.form.population.$dirty && myForm.form.population.$invalid" ng-click="add()">Add</button></td>
        </tr>

    </table>
    </form>
</body>
</html>

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

AngularJS CSRF Cookie not being set in Django backend during request submission

I am in the process of developing a web application using angularjs and django, and I am encountering an issue when submitting a form via an Ajax request. The problem I am facing is that when sending an Ajax request with angular (specifically ng-file-uplo ...

The distinction between a JSON file that is generated dynamically from a response and one that is

I've been working on configuring a bootstrap typeahead feature and here is the jquery code I am using: $(function () { $.ajax({ type: "GET", url: "http://example.com/search?callback=my_callback", data: { keyword: &apos ...

Executing a function in Angular using ng-init

I recently started working with angular and am developing an app that involves in-app purchases. Currently, I have a method to load the products that is triggered by ng-click. However, I want this method to be called when the page loads. I attempted using ...

The concealed field is not being established due to the Ajax AutoCompleteExtender OnClientItemSelected functionality

Currently, I am attempting to utilize the Ajax AutoCompleteExtender provided below: <asp:TextBox runat="server" Width="300" ID="tbxItem" CssClass="NormalUpper" /> <asp:AutoCompleteExtender ID="autoCompleteExtenderItemName" runat="server" Mini ...

It appears that the options attribute is being overlooked by the Angular toast directive

While working with Angular, I found the need for toast messages. In my search for answers, I came across an Angular Toast solution discussed in this question: Fire notification toaster in any controller angularjs However, when trying to set the location ...

Extracting data from cookies and saving it in the correct variable

A servlet sends three cookies to the client containing form entries for name, age, and surname with values submitted by the user. Upon receiving the cookies back from the client, the server needs to store: The value of the "name" cookie in a string vari ...

issue with accessing property in vue 2 simple examination

Hey there! I'm currently working on implementing Vue in a Laravel application, but I've run into some challenges. Essentially, my goal is to retrieve data from a GET request and generate results based on that data. However, I'm struggling to ...

The information from the data source is not getting filled in

I recently started working with Angular (Version 14.2.10) and I am trying to make a REST call to populate data in the UI. However, only the header is displayed without any data showing up. I suspect there is a minor issue that I can't seem to pinpoint ...

Using a function as a prop in Vue js to retrieve data from an API

I am facing an issue with a component that I want to decouple from the data fetching implementation. My goal is to be able to pass a data fetching callback as a prop. The reason for this is so that I can easily mock the data fetching process in storybook. ...

Enhancing data interpretation using jquery for json data

Is there a way to enhance this? I would like to streamline it, possibly using a loop because in the future I may need to display more than just 10 questions. I attempted to utilize variables with strings instead of "idX" but encountered issues. I prefer to ...

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

What is the best way to eliminate an element from a state using the useState hook?

I need help with generating a list of values from checkboxes. const [checkedState, setCheckedState] = useState({}); const handleOnChange = (e) => { if(e.target.checked === true){ setCheckedState({ ...checkedState, [e.target.name]: e.target.checke ...

Efficiently and consistently refreshing the DOM with information while maintaining page integrity

I'm currently developing a Single Page Application (SPA) that utilizes AJAX to dynamically load content into a specific div. The layout consists of a side accordion menu, where clicking on an item loads relevant information in a neighboring div. Howev ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

The implementation of local JSON instead of external JSONP in Angular

I am exploring the option of storing a json-file on the same server as my Angular app. I am wondering about how I can modify this code to read from a locally stored json file: ergastAPI.getDrivers = function() { return $http({ method: 'GET&apos ...

Tips for displaying a Rails action without a layout in html format using Ajax

Is it possible to render the new action without the application layout and without altering the current code structure? class FoobarController < ApplicationController def new @foobar = Foobar.new end # ... end When a user clicks on = link_ ...

Using Three JS to recycle the geometry of a previously imported object

Is there a way to efficiently re-use imported object geometries in Three JS without duplicating them in memory? I've tried writing a loader but it doesn't seem to update the geometry once loaded. var tmpGeo = geometries[ID]; if (!tmpGeo) { t ...

What is the best way to generate a new object by combining elements from an array and another object?

Attempting to create a new object by using an existing array. The goal is to generate an object that displays the following: { jack: 'jack', content: 'ocean'}, { marie: 'marie', content: 'pond'}, { james: 'jame ...

Guide on leveraging filter and map functions to modify an object

What is the process to adjust an existing object using map and filter? Two objects are provided below along with the desired output. let a = [ { a: "hi", b: 0 }, { a: "bye", b: 1 }, { a: "seeyou", b: 2 }, ]; let b = { hi ...