1

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

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.