Dynamic Angular Forms Validation in ngRepeat with ngMessage and live demo

angularjs dynamic form generation ng-repeat validation ng-form validation ng-form vs form angular dynamic form validation angularjs dynamic form builder ng-form submit angular dynamic form name

Validation of controls in ng-repeat is really easy, just we need a unique name for every control. I found many articles which use ngMessage but they validate all the controls together, if there is any invalid control, all the controls say the error message. I was in need to explore and try different tricks and found one easy way, which I want to share to same others time. In this article we are going to see a very simple case to have a ng-repeat and render label and input box and validate every control separately.

Before going in deep, let's have a look what we are going to do.

I don't want to show the error messages until user edit anything or try to submit the page.

Let's summaries what we need to run this application:

1. Angularjs
2. ngMessage

Let's see where we need to use the ng-repeat and validation, say we have following json:

[
    {"id": 1, "name": "Kevin Spacey", "email": "kevin@spacey.com"},
    {"id": 2, "name": "Robert De Niro", "email": ""},
    {"id": 3, "name": "Russell Crowe", "email": ""},
    {"id": 4, "name": "Brad Pitt", "email": ""},
    {"id": 5, "name": "Angelina Jolie", "email": ""}
];

We want to create a tabular structure to show the data on page and give the feature to add/edit the email and save to database. As you can see in my array, except the first record, all emails are empty. Go and type something in email textbox or click save button and see how it is working.

If you already checked the working demo then let's see the code, how it is working. As we known ngMessage work with form name and control name, we need to give every single control a unique name and some name (say "frmPage") to our form tag. To make unique name to every control, I try to combine the string "Ctrl" with $index of ngRepeat, so our control will have name like Ctrl0, Ctrl1, Ctrl2 .....CtrlN. Here is the code in ngRepeat

<input type='email' 
   name='Ctrl{{$index}}' // unique name 
   ng-model="item.email"
   ng-required='true'
   placeholder="Enter email address"
   class='form-control' />

We know ngMessages use FormName.ControlName.$error to show the message but we are creating our controls in a loop and creating dynamic name, so this code will now work, what we need to do is to use the array patter, like FormName[Control_Name].$error, see the below code first, ngShow is not needed if you if you want to show the error message on page load:

<div ng-messages="frmPage['Ctrl' +$index].$error"
     ng-show="frmPage['Ctrl' +$index].$dirty || frmPage.$submitted">
  <div ng-message="required" class='error'>Required</div>
  <div ng-message="email" class='error'>Invalid Email</div>
</div>

We can use ngShow or ngIf we want to show the error message only when user change the value or try to submit the page and if there is any invalid value show the error then only, that's why I use ngShow here.

We don't have any special code in our controller, just the hard coded list of users

app.controller('pageCtrl', ['$scope', function($scope) {  
  $scope.list =[
    {"id": 1, "name": "Kevin Spacey", "email": "kevin@spacey.com"},
    {"id": 2, "name": "Robert De Niro", "email": ""},
    {"id": 3, "name": "Russell Crowe", "email": ""},
    {"id": 4, "name": "Brad Pitt", "email": ""},
    {"id": 5, "name": "Angelina Jolie", "email": ""}
  ];   
}]);

Here is the complete HTML Code:

<div ng-app="app" class="container">
  <h1>Dynamic Angular Forms Validation in ngRepeat with ngMessage</h1>
  <hr />
  <form name="frmPage" ng-controller="pageCtrl" novalidate>

    <div class="row form-group" ng-repeat="item in list">
      <div class="control-lable col-md-2">{{item.id}}. {{item.name}}</div>
      <div class="col-md-6">
        <input type='email' 
               name='Ctrl{{$index}}'
               ng-model="item.email"
               ng-required='true'
               placeholder="Enter email address"
               class='form-control' />
      </div>
      <div class="col-md-4">
        <div ng-messages="frmPage['Ctrl' +$index].$error"
             ng-show="frmPage['Ctrl' +$index].$dirty || frmPage.$submitted">
          <div ng-message="required" class='error'>Required</div>
          <div ng-message="email" class='error'>Invalid Email</div>
        </div>
      </div>
    </div>
    <br>
    <div class='row'>
      <div class='col-md-5 pull-right'>
        <input type='submit' class='btn btn-success '  />
      </div>
    </div>    
    <pre class='col-md-6 col-md-offset-2'>{{list | json}}</pre>
  </form>     
</div>
Ali Adravi Having 10+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 8 years and still with the same company. Always ready to learn new technologies and tricks.
  • angularjs
  • ngMessage
By Ali Adravi On 20 Jan, 17  Viewed: 412

Other blogs you may like

Angularjs powerful paging on table and searching with delay and demo

Paging on table is the basic requirement and most of us look for some grid so it can provide the complete feature of paging and sorting but in Angularjs it is so easy that anyone can achieve it by writing some code. I checked and found most of the available code give the paging feature in for 1 to... By Ali Adravi   On 14 Aug 2015  Viewed: 7,427

Angularjs Cascading Dropdown/Select with demo

Cascading dropdown with angularjs is easier than MVC and ASP.Net. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change... By Ali Adravi   On 06 Aug 2015  Viewed: 30,548

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 12,292

Custom Directives in AngularJS with example and demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are... By Ali Adravi   On 29 Jul 2015  Viewed: 2,263

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 1

Search sort Insert update and delete are the basic features we need to learn first to learn any language, In this article we will try to create these features with Web API, bootstrap modal popup and ui.router. We will use enetity framework code first to save and retrieve data from database. We... By Ali Adravi   On 28 Jul 2015  Viewed: 22,188