ahm_selim
ahm_selim

Reputation: 141

AngularJS validation error for input with brackets

When using AngularJS form validation it work smoothly except the following part when validating select input with brackets

<div class="form-group" ng-class="{'has-error': editDorm.classId.$invalid}">
      <div class="col-sm-10">
        <select class="form-control" ng-model="form.classId" name="classId[]" multiple required>
          <option ng-repeat="class in classes" value="{{class.id}}">{{class.className}}</option>
        </select>
      </div>
    </div>

Appreciate your help. thanks

Upvotes: 1

Views: 112

Answers (1)

PSL
PSL

Reputation: 123739

You would need to use bracket notation, name of the element with the sq: brackets are added as key in the form controller, so you need to refer to the modal instance from form controller instance as editDorm['classId[]']. When in doubt always print the form instance in the html, i.e {{editDorm}} that will show the kvp.

i.e:

 ng-class="{'has-error': editDorm['classId[]'].$invalid}"

angular.module('app', []).run(function($rootScope) {
  $rootScope.classes = [{
    id: 1,
    className: 'class1'
  }, {
    id: 2,
    className: 'class2'
  }];
})
.has-error {
  border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <form name="editDorm">
    <div class="form-group" ng-class="{'has-error': editDorm['classId[]'].$invalid}">
      <div class="col-sm-10">
        <select class="form-control" ng-model="form.classId" name="classId[]" multiple required>
          <option ng-repeat="class in classes" value="{{class.id}}">{{class.className}}</option>
        </select>
      </div>
    </div>
  </form>
</div>

Another Note: Recommended way to use select is to use ng-options not ng-repeat, it is easy to work with.

You would do:

     <select class="form-control"
              ng-model="form.classId" 
              name="classId[]" 
              ng-options="class.id as class.className for class in classes"
              multiple required>
     </select>

Upvotes: 1

Related Questions