Tips for validating a form in AngularJs when utilizing the ng-repeat directive

Within my AngularJS form, I successfully implemented validation for an email field. However, upon adding another email field, the validation applies to all items. My intention is for only the first field to be validated as required.

<form novalidate name="myForm">
  <button class="btn btn-info btn-sm" ng-click="addNewChoice('email')">
    <i class="fa fa-at"></i> Add Email
  </button>
  <br>
  <div class="form-group row">
    <div data-ng-repeat="email in emails">
      <div class="col-md-4 col-sm-12" ng-class="{
                                       'has-error'   :isInputInvalid(myForm.email1),
                                       'has-success' : isInputValid(myForm.email1)
                                        }">
        <label for="email{{ $index + 1}}">Email {{ $index + 1}}</label>
        <input type="email" class="form-control" name="email{{ $index + 1}}" ng-model="formModel.emails[$index + 1]" id="email{{ $index + 1}}" placeholder="Enter email" required>
        <span class="help-block" ng-show="myForm.email1.$error.required && myForm.email1.$dirty">Required</span>
        <span class="help-block" ng-show="myForm.email1.$error.email">Email not valid!</span>
      </div>
    </div>

  </div>
</form>

jsFiddle

Answer №1

To target only the first item in a list generated by the ng-repeat directive in AngularJS, you can easily use the $first property.

Instead of just using required, you can switch to ng-required with the following syntax:

ng-required="{{$first}}"

By incorporating $first into your validation logic, you can exclude validations for emails beyond the first one!

Check out the updated fiddle

EDIT: Based on my understanding, it seems like you only want to validate the first email input. If you are facing issues where the second email is flagged as invalid even if the first one is incorrect, please review this alternative fiddle with separate validations for each email entry.

Answer №2

Delete the section "&& myForm.email1.$dirty" from the "Required span" divider

Answer №3

To successfully implement the ng-repeat loop, it is essential to exclude the initial element and introduce a fresh choice email.

Answer №4

To show content only when it is the first item in a list, you can use ng-if="$first"

Here's a sample code snippet to demonstrate this:

var myApp = angular.module('appMy', []);

myApp.controller('myCtrl', function($scope) {
  console.log("hguy");
  $scope.formModel = {};

  $scope.emails = [{
    id: 'email1'
  }];

  $scope.isInputValid = function(input) {

    return input.$dirty && input.$valid;
  }

  $scope.isInputInvalid = function(input) {
    return input.$dirty && input.$invalid;
  }
  
  $scope.addNewChoice = function(val) {


var newItemNo2 = $scope.emails.length+1;
$scope.emails.push({'id':'email'+newItemNo2});


};

});
.help-block {
  color: #b34848;
}

.has-error label {
  color: #a94442;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div class="container" ng-app="appMy">

  <div ng-controller="myCtrl">
    <form novalidate name="myForm">
      <button class="btn btn-info btn-sm" ng-click="addNewChoice()">
        <i class="fa fa-at"></i> Add Email
      </button>
      <br>
      <div class="form-group row">
        <div data-ng-repeat="email in emails">
          <div class="col-md-4 col-sm-12" ng-class="{
                           'has-error'   :isInputInvalid(myForm.email1),
                           'has-success' : isInputValid(myForm.email1)
                       }">
            <label for="email{{ $index + 1}}">Email {{ $index + 1}}</label>
            <input type="email" class="form-control" name="email{{ $index + 1}}" ng-model="formModel.emails[$index + 1]" id="email{{ $index + 1}}" placeholder="Enter email" required>
        <span ng-if="$first" class="help-block" ng-show="myForm.email1.$touched && myForm.email1.$invalid">Required</span>
            <span class="help-block" ng-show="myForm.email{{ $index + 1}}.$error.email">Email not valid!</span>
          </div>
        </div>

      </div>
    </form>
  </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

Verifying the invocation of a callback function through the use of $rootScope.$broadcast and $scope.$on

I have been testing to see if a callback was called in my controller. Controller (function () { 'use strict'; angular .module('GeoDashboard') .controller('CiudadCtrl', CiudadCtrl); CiudadCtrl.$i ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Retrieve selected value from HTML input with datalist and use it as an argument in a method

I have a datalist in my HTML input where I need to pass the selected value into JavaScript / Angular. It must be passed because the datalist is being used in an HTML table with multiple entries. Most examples I've come across show how to grab the valu ...

Creating a semi-circle donut chart with Highcharts using the Highcharts-ng library

I have been working on integrating a Highcharts Semi-circle donut chart into my angular application using the Highcharts-ng directive. However, I seem to be facing an issue where the plotOptions section is being skipped entirely, leading to a full circle p ...

"Array.Find function encounters issues when unable to locate a specific string within the Array

Currently, I am utilizing an array.find function to search for the BreakdownPalletID when the itemScan value matches a SKU in the array. However, if there is no match found, my application throws a 'Cannot read property breakdownPalletID of undefined& ...

Having trouble with the filtering feature in Material UI Datagrid

I'm currently using Material UI Data Grid to display a table on my website. The grid has an additional filter for each column, but when I click on the filter, it hides behind my Bootstrap Modal. Is there a way to bring it to the front? https://i.stac ...

Launch a new email window in Outlook from a server using C#

Currently, I am working on a feature where users can select multiple product links and have the option to email those links to someone. The functionality works perfectly fine on my local machine, but when deployed, it throws an exception as shown below: ...

Sequentially calling URLs in Selenium NodeJS to retrieve the page source of each

I am trying to open URLs based on the IDs available in an array and retrieve the unique PageSource for each. However, when I run the code below, only the PageSource of the last element is being returned. For example, if the body of each URL looks like: ...

Launching the mongo-dev-server for the project's local mongo database while utilizing an external MongoDB during Meteor Run

Q. How can I leverage mongo-dev-server to utilize an internal MongoDB in my Meteor project while also using an external MongoDB with 'export MONGO_URL'? Explanation: I know that MongoDB should be fully installed for production mode, but sometime ...

I can't seem to figure out why I constantly struggle with adding a check mark to a checkbox using

Take a look at the code I've provided below : HTML : <input type="checkbox" name="xyz[1][]" id="sel_44" style="margin:2px;" value="12345" onclick="myClick(this)"> Javascript : <script> $('#sel_44').attr("checked", true); < ...

The parameter 'string | JwtPayload' cannot be assigned to the parameter 'string'

Utilizing Typescript alongside Express and JWT for Bearer Authorization presents a specific challenge. In this situation, I am developing the authorize middleware with JWT as specified and attempting to extricate the current user from the JWT token. Sampl ...

Display or conceal section based on selected checkboxes

I'm currently working on a JavaScript script that involves showing/hiding elements based on radio button and checkbox selections. The goal is to reveal a hidden section when certain checkboxes are checked, as illustrated in the screenshot below: http ...

Adjust the size of a stacked object on top of another object in real-time

Currently, I am working on a project using three.js where users have the ability to modify the dimensions of a 3D model dynamically. The issue I'm encountering is similar to a problem I previously posted about stacking cubes together, which you can fi ...

A guide on seamlessly combining AngularJS and ASP.NET Web API

As a newcomer to AngularJS and ASP.NET, I have been struggling to find the right answers and am feeling more confused than ever. My current challenges include: 1) How can I seamlessly integrate an AngularJS application with an ASP.NET MVC web API using S ...

Switch up the font style of the title element

Is it possible to modify the font-family of the title attribute in an input field using either JavaScript or jQuery? <input type="text" title="Enter Your Name" id="txtName" /> ...

Sending state information through props in a Vuex environment

One of the challenges I am facing is how to make a reusable component that can display data from the store. My idea is to pass the name of the store module and property name through props, as shown below: <thingy module="module1" section=" ...

Changing SVG containing image tags into HTML canvas

I'm attempting to convert an SVG file to an HTML canvas, and everything works perfectly until I introduce the image element in the SVG. When I include image elements, the canvg function stops working. Below is the code I used to convert the SVG to ca ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

Reducing Image Size in JavaScript Made Easy

I need help with a project where I want the image to shrink every time it's clicked until it disappears completely. I'm struggling to achieve this, can someone assist me? Here is the HTML code I have: <html lang="en" dir="l ...

Access Sharepoint from an external site

Looking for assistance with a SharePoint list containing columns for Name, Position, Office, and Salary. Upon logging in with specific credentials to the SharePoint website, I need to retrieve all items from the list and showcase them on my own website. ...