Karl Gjertsen Karl Gjertsen - 5 months ago 14
AngularJS Question

Angular form is valid with unselected select

I have an Angular form that has a select, which is marked as required.

When the form loads, a Choose a region message is shown to prompt the user to make a selection.

However, the form is valid even if it does not have a valid selection.

If the user selects a valid option, then selects Choose a Region the form validation marks the form as invalid.

Why is the form not invalid to start with?

Code:

<div ng-controller="MyCtrl">
<form name="myForm">
<select name="region"
ng-model="regionId"
ng-options="region.id as region.name for region in regions"
ng-selected="region.id"
required>
<option value="">-- choose a region --</option>
</select>
</form>
</div>


Controller:

function MyCtrl($scope) {
var myRegions = [{ id: 1, name: "England" },
{ id: 2, name: "Wales" },
{ id: 3, name: "Northern Ireland" },
{ id: 4, name: "Scotland" }
];
$scope.regions = myRegions;
$scope.regionId = 0;
}


Here is the code in a jsfiddle.

Answer

Your form is valid because you set initial value $scope.regionId = 0;. Just remove it or replace on $scope.regionId = "";.

Live example on jsfiddle.

angular.module('ExampleApp', [])
  .controller('ExampleController', function() {
    var vm = this;
    var myRegions = [{
      id: 1,
      name: "England"
    }, {
      id: 2,
      name: "Wales"
    }, {
      id: 3,
      name: "Northern Ireland"
    }, {
      id: 4,
      name: "Scotland"
    }];
    vm.regions = myRegions;
    vm.regionId = "";
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController as vm">
    <form name="myForm">
      isValid: {{myForm.$valid}}
      <br>
      <select name="region" ng-model="vm.regionId" ng-options="region.id as region.name for region in vm.regions" ng-selected="vm.region.id" required>
        <option value="">-- choose a region --</option>
      </select>
    </form>
  </div>
</div>

Comments