user2919905
user2919905

Reputation: 63

How to restrict input field length (max length) using <md-autocomplete>

I would like to achieve the behavior to restrict/limit users entr to only 10 numbers for ex:

Anyone know how to do this?

I do see that they have an attribute md-input-maxlength, but i am not able to get it work, or find an example.

Appreciate your inputs.

Upvotes: 4

Views: 7227

Answers (5)

pcchan
pcchan

Reputation: 21

Extend from John Smith's answer, you can try

md-search-text-change="searchText = searchText.substring(0,10)"

Upvotes: 2

user1242321
user1242321

Reputation: 1696

Here's the working code:

    <md-autocomplete flex=""
                       required
                       ng-init="searchText=''"
                       md-input-name="autocompleteAddField"
                       md-input-minlength="2"
                       md-input-maxlength="10"
                       md-no-cache="true"
                       md-selected-item="newE.add"
                       md-search-text="searchText"
                       md-items="item in vm.queryAddressSearch(searchText)"
                       md-item-text="item.address"
                       md-require-match=""
                       md-floating-label="Address">
        <md-item-template>
          <span md-highlight-text="searchText">{{item.address}}</span>
        </md-item-template>
        <div ng-messages="newEntityForm.autocompleteAddField.$error" ng-if="newEntityForm.autocompleteAddField.$touched">
          <div ng-message="required">You <b>must</b> have a user address.</div>
          <div ng-message="md-require-match">Please select an existing address.</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>

Upvotes: 1

Sreeragh A R
Sreeragh A R

Reputation: 3021

Combine 'md-maxlength' and 'maxlength' eg. input type="text" md-maxlength="512" maxlength="512"

Upvotes: 0

John Smith
John Smith

Reputation: 2341

I don't think there is currently an easy way to do it. However, as a hacky workaround you can use md-search-text-change and whenever the value is longer than X, you can just overwrite it with the first X characters of the value.

Example pen here

Keep in mind though, changing the text to a substring of it will cause another call for the text change event.

Upvotes: 1

Pranab Mitra
Pranab Mitra

Reputation: 389

You can use ng-maxlength="10". Here is an example. If the user type more than 10 characters then the form will be invalid. You can check this out.

<form name="form">
  <input type="text" ng-model="model" id="input" name="input" ng-maxlength="10" />
  <hr>
  input valid? = <code>{{form.input.$valid}}</code><br>
  model = <code>{{model}}</code>
</form>

Upvotes: -1

Related Questions