AngularJS - implementing validation within ng-repeat for name attributes in arrays

I am currently working on a project that utilizes ASP.NET MVC 5 on the server side. As outlined in this particular post, my form on the server side is designed to accept an array of objects as a parameter. This requires me to structure the name attributes within my view in the following manner.

QualificationList[0].Degree
QualificationList[0].Institute
QualificationList[1].Degree
QualificationList[1].Institute
QualificationList[2].Degree
QualificationList[2].Institute
.
.
.
.
QualificationList[n].Degree
QualificationList[n].Institute

It's important to note that this isn't a duplicated query, as I have already tried numerous solutions from sources like StackOverflow and others. The complexity lies in the fact that the value of n isn't fixed. By utilizing ng-repeat, I can successfully render it as follows.

<div ng-form="myForm" class="form-group" ng-repeat="q in QualificationList">
     <div class="col-md-9">
         <input class="form-control text-box single-line" ng-model="QualificationList[$index].Degree" ng-required="true" name="QualificationList[{{$index}}].Degree" type="text" value="" />
         <span ng-show="QualificationList[$index].Degree.$invalid">The Degree field is required</span>
      </div>
      <div class="col-md-3">
          <input class="form-control text-box single-line" ng-model="QualificationList[$index].Institute" ng-required="true" name="QualificationList[{{$index}}].Institute" type="text" value="" />
          <span ng-show="QualificationList[$index].Institute.$invalid">The Institute field is required</span>
      </div>
</div>

As demonstrated above, my goal is to validate the user-entered values for both Degree and Institute. I have also experimented with this proposed solution, but it did not yield the desired results.

How can I showcase validation errors? It's essential to acknowledge that for simplicity, I'm focusing solely on two fields here - namely Degree and Institute. However, within my actual project, there are over 20 fields that require varying forms of validations (such as ng-pattern, email, etc.)

To keep things straightforward, I've created a fiddle which you can access here: http://jsfiddle.net/wa5y5L15/29/

Answer №1

Your approach of using a ngForm for each list item is correct for individual validation, but naming and referencing the inputs can be tricky in this setup.

To simplify things, since each ngForm has an isolated scope, just use a generic name like 'Degree' or 'Institute'. Remember to prefix it with the form's name in the ng-show expression:

<div ng-form="myForm" class="form-group" ng-repeat="q in QualificationList">
     <div class="col-md-9">
         <input class="form-control text-box single-line" ng-model="QualificationList[$index].Degree" ng-required="true" name="Degree" type="text" value="" />
         <span ng-show="myForm.Degree.$invalid">The Degree field is required</span>
      </div>
      <div class="col-md-3">
          <input class="form-control text-box single-line" ng-model="QualificationList[$index].Institute" ng-required="true" name="Institute" type="text" value="" />
          <span ng-show="myForm.Institute.$invalid">The Institute field is required</span>
      </div>
</div> 

Check out this helpful article:

http://scotch.io/tutorials/building-dynamic-angular-forms-with-ngrepeat-and-ngform

EDIT:

If you're having trouble using the form model, you can check properties in the controller scope using regular expressions (and include them in your ngShow). For example, if you just need a non-empty string, try something like this:

<div ng-form="myForm" class="form-group" ng-repeat="q in QualificationList">
    <div class="col-md-10 col-xs-10">
        <div class="col-md-6 col-xs-6">
            <input class="form-control text-box single-line" ng-model="QualificationList[$index].Degree" ng-required="true" name="QualificationList[{{$index}}].Degree" type="text" value="" /> 
            <span ng-show="!QualificationList[$index].Degree">The Institute field is required</span>
        </div>
        <div class="col-md-6 col-xs-6">
            <input class="form-control text-box single-line" ng-model="QualificationList[$index].Institute" ng-required="true" name="QualificationList[{{$index}}].Institute" type="text" value="" /> 
            <span ng-show="!QualificationList[$index].Institute">The Institute field is required</span>
        </div>
    </div>
</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

jQuery: What's the Difference Between Triggering a Click and Calling a Function?

Imagine having certain actions assigned to a link using .click or .live, and wanting to repeat the same action later without duplicating code. What would be the right approach and why? Option 1: $('#link').click(function(){ //do stuff }); //c ...

What could be the reason for a jQuery script failing to execute when included in a PHP include statement from a different PHP page?

I'm currently working with javascript and php to manage cookies across different pages. On one page, I have a script that sets a value in a cookie variable and I want to retrieve that value on another page. Let's say the first page is named page1 ...

The RxDB Angular2-cli error message. "Cannot assign a 'Promise<void>' to a 'Promise<any>' parameter."

https://i.sstatic.net/50vu6.png I've been grappling with getting RxDB to function properly in a fresh project I initiated using the Angular CLI. Here's my process: ng new <Projectname> After that, I installed RxDB by running: npm instal ...

What is the best way to initiate an event using the onMousewheel function?

I am currently working on a WebGL application where I have a sphere object that utilizes orbit controls for zooming in and out. My goal is to set up an event for the mousewheel so that when I zoom on the WebGL block, the corresponding map location also zo ...

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

Confirm the checkboxes that are necessary

In the realm of my AngularJS project, I am eager to develop a terms and conditions form. Among multiple checkboxes, only select few are deemed necessary. My aim is to activate the submit button solely when all required checkboxes have been checked. Below ...

Node.js encountering req.body as undefined when using form-data as the content-type

After creating a small demonstration for this form-data passing API, I attempted to test it using Postman. However, I encountered an issue where no data was being retrieved. Code const http = require("http"); const express = require("expres ...

Oops: Looks like there is already a request for 'PUBLIC_requestAccounts' pending from http://localhost:3000. Just hold tight for now

There comes a moment when an unexpected error arises and fails to establish a connection with your wallet. if (window.ethereum) { console.log("11") const connect = async () => { const account = await window.ethereum.request({ ...

Error: Unrecognized primary operator: $sortby

We have a web application built using Node.js and Mongoose, running on Ubuntu Linux servers hosted on DigitalOcean VPS. One of our Mongoose queries includes a text index with the following operators: less than / equal to limit order by This is how the ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...

Navigating through tabs in a Meteor application: How to maintain the active tab when using the back button

I am working on a multi-page meteor application where each page includes a navigation template. To switch between pages, I am using iron-router. The user's current page is indicated by setting the appropriate navigation link's class to 'ac ...

Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link ...

Avoid creating empty blocks in ASP.NET MVC

I'm working on some back-end code Take a look at the code snippet below [HttpGet] public ActionResult GetQuestions() { var _id = TempData["ID"]; var questBlock = db.QuestionBlocks .Where(x => x.Interview_Id == ...

What is the best way to include multiple search parameters in a Node.js URL?

I'm currently working on a project involving react, node, express, and postgress. My main challenge right now is figuring out how to use express routes to pass multiple parameters. For example: Here's the route I am trying to work with: //Get en ...

Understanding the optimal scenarios for utilizing inline functions in button onClick events in JavaScript/React.js

When it comes to assigning event handlers to buttons, there are various styles to choose from. Is there a specific scenario where using an inline function for the button's onClick event handler is recommended? onClick={props.handleDeleteOption(props. ...

Prevent scale animation for a specific section of the icon using CSS

I need help in preventing the scale animation of the :before part of the icon class from occurring when the button is hovered. The current behavior is causing the arrow to look distorted on hover... Link to the code on Codepen HTML <div class="se ...

The Gulpfile.js encountered an error while trying to load

My Visual Studio task runner is having trouble loading the gulp file. I am currently using VS2017 v15.9.4, but the project was developed some years ago. Failed to run "...\Gulpfile.js"... cmd.exe /c gulp --tasks-simple assert.js:350 throw err; ...

Creating a div that functions as a scrollbar controller

I am in search of a unique way to customize the scrolling functionality on my application, resembling more of a navbar that scrolls. However, I have not been able to find any existing plugins that meet my specific requirements. My inquiry includes: Whic ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

Perform an Ajax request to a C# Controller Function

In my javascript file named "data handling.js" within a folder labeled "JS", you'll find the following piece of code: document.getElementById('submit-new-project').addEventListener("click", function () { var ProjectName = document.getEl ...