Search code examples
javascriptangularjsangular-materialmd-select

Angular material md-select empty value validation not working


In md-select, I have added an empty md-option item and this select field is a required field. But Validation is not working when I selected 'Choose One' item with value as empty.

Codepen : http://codepen.io/anon/pen/ygrJLG

<div ng-controller="AppCtrl" ng-cloak="" layout="column" layout-align="center center" layout-padding="" class="selectdemoValidations" ng-app="MyApp">
  <form name="myForm">

    <div layout="row" layout-align="start" flex="">
      <md-input-container flex>
        <label>Favorite Color</label>
        <md-select name="favoriteColor" ng-model="favoriteColor" required="" >
          <md-option value=''>Choose One</md-option>
          <md-option ng-value=color ng-repeat="color in colors">{{color}}</md-option>         
        </md-select>
        <div class="errors" ng-messages="myForm.favoriteColor.$error">
          <div ng-message="required">Required</div>
        </div>
      </md-input-container>
    </div>

    <div layout="row" layout-align="start">
      <md-checkbox ng-model="myForm.$invalid" disabled="">Form Invalid</md-checkbox>
      <md-checkbox ng-model="myForm.$dirty" disabled="">Form Dirty</md-checkbox>
      <md-checkbox ng-model="myForm.$submitted" disabled="">Form Submitted</md-checkbox>
      <md-checkbox ng-model="myForm.favoriteColor.$touched" disabled="">Select Touched</md-checkbox>
    </div>

    <div layout="row" layout-align="end" flex="">
      Selected Color is {{favoriteColor}}
      <md-button ng-click="clearValue()" ng-disabled="!favoriteColor">Clear</md-button>
      <md-button ng-click="save()" class="md-primary">Save</md-button>
    </div>
  </form>
</div>

Solution

  • You can fix it with that:

    $scope.$watch('favoriteColor', function(val)
    {
        if (!val) $scope.favoriteColor = null;
    });
    

    Why? Because there is a difference between null and undefined:

    null = the value set to empty value

    undefined = the value has not been initialized