Sam Sam - 6 months ago 21
AngularJS Question

How to add validation attributes to md-autocomplate angular material directive

I'm using version 0.7.1 of angular material. I'm using the autocomplete as described here:
Autocomplete demo

However, it doesn't seem to support validation logic, even though it generates a textarea:
Autocomplete directive documentation

I imagine that I can add logic in the querySearch function to switch ng-valid to ng-invalid. Is this correct? If this is the case, then I need a handle on the md-autocomplete, but this is difficult, because the name attribute gets removed.

Answer

Quick update, got the solution on Angular Material site (Latest release 1.0.0-), https://material.angularjs.org/latest/demo/autocomplete.

You will find that 'required' and 'ng-messages' are supported now.

<div ng-controller="DemoCtrl as ctrl" layout="column" ng-cloak>
<md-content class="md-padding">
<form ng-submit="$event.preventDefault()" name="searchForm">
  <p>The following example demonstrates floating labels being used as a normal form element.</p>
  <div layout-gt-sm="row">
    <md-input-container flex>
      <label>Name</label>
      <input type="text"/>
    </md-input-container>
    <md-autocomplete flex required
        md-input-name="autocompleteField"
        md-input-minlength="2"
        md-input-maxlength="18"
        md-no-cache="ctrl.noCache"
        md-selected-item="ctrl.selectedItem"
        md-search-text="ctrl.searchText"
        md-items="item in ctrl.querySearch(ctrl.searchText)"
        md-item-text="item.display"
        md-floating-label="Favorite state">
      <md-item-template>
        <span md-highlight-text="ctrl.searchText">{{item.display}}</span>
      </md-item-template>
      <div ng-messages="searchForm.autocompleteField.$error" ng-if="searchForm.autocompleteField.$touched">
        <div ng-message="required">You <b>must</b> have a favorite state.</div>
        <div ng-message="minlength">Your entry is not long enough.</div>
        <div ng-message="maxlength">Your entry is too long.</div>
      </div>
    </md-autocomplete>
  </div>
</form>

Comments